aboutsummaryrefslogtreecommitdiffstats
path: root/src/net/java/sip/communicator/impl/neomedia/MediaConfigurationImpl.java
blob: d561c92c507ef74e34f1e341b8152818d9130d7f (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
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
/*
 * 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.neomedia;

import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.concurrent.*;

import javax.media.*;
import javax.media.MediaException;
import javax.media.protocol.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.table.*;

import net.java.sip.communicator.plugin.desktoputil.*;
import net.java.sip.communicator.plugin.desktoputil.TransparentPanel;
import net.java.sip.communicator.util.*;

import org.jitsi.impl.neomedia.*;
import org.jitsi.impl.neomedia.device.*;
import org.jitsi.service.audionotifier.*;
import org.jitsi.service.configuration.*;
import org.jitsi.service.neomedia.*;
import org.jitsi.service.neomedia.codec.*;
import org.jitsi.service.neomedia.device.*;
import org.jitsi.service.neomedia.event.*;
import org.jitsi.service.resources.*;
import org.jitsi.util.OSUtils;
import org.jitsi.util.swing.*;

/**
 * Implements <tt>MediaConfigurationService</tt> i.e. represents a factory of
 * user interface which allows the user to configure the media-related
 * functionality of the application.
 *
 * @author Lyubomir Marinov
 * @author Damian Minkov
 * @author Yana Stamcheva
 * @author Boris Grozev
 * @author Vincent Lucas
 */
public class MediaConfigurationImpl
    implements ActionListener,
               MediaConfigurationService
{
    /**
     * Creates a new listener to combo box and affect changes to the audio level
     * indicator. The level indicator is updated via a thread in order to avoid
     * deadlock of the user interface.
     */
    private class AudioLevelListenerThread
        implements ActionListener,
                   HierarchyListener
    {
        /**
         * Listener to update the audio level indicator.
         */
        private final SimpleAudioLevelListener audioLevelListener
            = new SimpleAudioLevelListener()
            {
                public void audioLevelChanged(int level)
                {
                    soundLevelIndicator.updateSoundLevel(level);
                }
            };

        /**
         * The audio system used to get and set the sound devices.
         */
        private AudioSystem audioSystem;

        /**
         * The combo box used to select the device the user wants to use.
         */
        private JComboBox comboBox;

        /**
         * The current capture device.
         */
        private AudioMediaDeviceSession deviceSession;

        /**
         * The new device chosen by the user and that we need to initialize as
         * the new capture device.
         */
        private AudioMediaDeviceSession deviceSessionToSet;

        /**
         * The indicator which determines whether
         * {@link #setDeviceSession(AudioMediaDeviceSession)} is to be invoked
         * when {@link #deviceSessionToSet} is <tt>null</tt>.
         */
        private boolean deviceSessionToSetIsNull;

        /**
         * The <tt>ExecutorService</tt> which is to asynchronously invoke
         * {@link #setDeviceSession(AudioMediaDeviceSession)} with
         * {@link #deviceSessionToSet}.
         */
        private final ExecutorService setDeviceSessionExecutor
            = Executors.newSingleThreadExecutor();

        private final Runnable setDeviceSessionTask
            = new Runnable()
            {
                public void run()
                {
                    AudioMediaDeviceSession deviceSession = null;
                    boolean deviceSessionIsNull = false;

                    synchronized (AudioLevelListenerThread.this)
                    {
                        if ((deviceSessionToSet != null)
                                || deviceSessionToSetIsNull)
                        {
                            /*
                             * Invoke #setDeviceSession(AudioMediaDeviceSession)
                             * outside the synchronized block to avoid a GUI
                             * deadlock.
                             */
                            deviceSession = deviceSessionToSet;
                            deviceSessionIsNull = deviceSessionToSetIsNull;
                            deviceSessionToSet = null;
                            deviceSessionToSetIsNull = false;
                        }
                    }

                    if ((deviceSession != null) || deviceSessionIsNull)
                    {
                        /*
                         * XXX The method blocks on Mac OS X for Bluetooth
                         * devices which are paired but disconnected.
                         */
                        setDeviceSession(deviceSession);
                    }
                }
            };

        /**
         * The sound level indicator used to show the effectiveness of the
         * capture device.
         */
        private SoundLevelIndicator soundLevelIndicator;

        /**
         *  Provides an handler which reads the stream into the
         *  "transferHandlerBuffer".
         */
        private final BufferTransferHandler transferHandler
            = new BufferTransferHandler()
            {
                public void transferData(PushBufferStream stream)
                {
                    try
                    {
                        stream.read(transferHandlerBuffer);
                    }
                    catch (IOException ioe)
                    {
                    }
                }
            };

        /**
         * The buffer used for reading the capture device.
         */
        private final Buffer transferHandlerBuffer = new Buffer();

        /**
         * Creates a new listener to combo box and affect changes to the audio
         * level indicator.
         *
         * @param audioSystem The audio system used to get and set the sound
         * devices.
         * @param comboBox The combo box used to select the device the user
         * wants to use.
         * @param soundLevelIndicator The sound level indicator used to show the
         * effectiveness of the capture device.
         */
        public AudioLevelListenerThread(
                AudioSystem audioSystem,
                JComboBox comboBox,
                SoundLevelIndicator soundLevelIndicator)
        {
            init(audioSystem, comboBox, soundLevelIndicator);
        }

        /**
         * Refresh combo box when the user click on it.
         *
         * @param ev The click on the combo box.
         */
        public void actionPerformed(ActionEvent ev)
        {
            synchronized (this)
            {
                deviceSessionToSet = null;
                deviceSessionToSetIsNull = true;
                setDeviceSessionExecutor.execute(setDeviceSessionTask);
            }

            CaptureDeviceInfo cdi;

            if (comboBox == null)
            {
                cdi
                    = soundLevelIndicator.isShowing()
                        ? audioSystem.getSelectedDevice(
                                AudioSystem.DataFlow.CAPTURE)
                        : null;
            }
            else
            {
                Object selectedItem
                    = soundLevelIndicator.isShowing()
                        ? comboBox.getSelectedItem()
                        : null;

                cdi
                    = (selectedItem
                            instanceof
                                DeviceConfigurationComboBoxModel.CaptureDevice)
                        ? ((DeviceConfigurationComboBoxModel.CaptureDevice)
                                selectedItem)
                            .info
                        : null;
            }

            if (cdi != null)
            {
                for (MediaDevice md: mediaService.getDevices(
                            MediaType.AUDIO,
                            MediaUseCase.ANY))
                {
                    if (md instanceof AudioMediaDeviceImpl)
                    {
                        AudioMediaDeviceImpl amd = (AudioMediaDeviceImpl) md;

                        if (cdi.equals(amd.getCaptureDeviceInfo()))
                        {
                            try
                            {
                                MediaDeviceSession deviceSession
                                    = amd.createSession();
                                boolean deviceSessionIsSet = false;

                                try
                                {
                                    if (deviceSession instanceof
                                            AudioMediaDeviceSession)
                                    {
                                        synchronized (this)
                                        {
                                            deviceSessionToSet
                                                = (AudioMediaDeviceSession)
                                                    deviceSession;
                                            deviceSessionToSetIsNull
                                                = (deviceSessionToSet == null);
                                            setDeviceSessionExecutor.execute(
                                                    setDeviceSessionTask);
                                        }
                                        deviceSessionIsSet = true;
                                    }
                                }
                                finally
                                {
                                    if (!deviceSessionIsSet)
                                        deviceSession.close();
                                }
                            }
                            catch (Throwable t)
                            {
                                if (t instanceof ThreadDeath)
                                    throw (ThreadDeath) t;
                            }
                            break;
                        }
                    }
                }
            }
        }

        public void hierarchyChanged(HierarchyEvent ev)
        {
            if ((ev.getChangeFlags() & HierarchyEvent.SHOWING_CHANGED) != 0)
            {
                SwingUtilities.invokeLater(
                        new Runnable()
                        {
                            public void run()
                            {
                                actionPerformed(null);
                            }
                        });
            }
        }

        /**
         * Creates a new listener to combo box and affect changes to the audio
         * level indicator.
         *
         * @param audioSystem The audio system used to get and set the sound
         * devices.
         * @param comboBox The combo box used to select the device the user
         * wants to use.
         * @param soundLevelIndicator The sound level indicator used to show the
         * effectiveness of the capture device.
         */
        public void init(
                AudioSystem audioSystem,
                JComboBox comboBox,
                SoundLevelIndicator soundLevelIndicator)
        {
            this.audioSystem = audioSystem;

            if (this.comboBox != comboBox)
            {
                if (this.comboBox != null)
                    this.comboBox.removeActionListener(this);
                this.comboBox = comboBox;
                if (comboBox != null)
                    comboBox.addActionListener(this);
            }

            if (this.soundLevelIndicator != soundLevelIndicator)
            {
                if (this.soundLevelIndicator != null)
                    this.soundLevelIndicator.removeHierarchyListener(this);
                this.soundLevelIndicator = soundLevelIndicator;
                if (soundLevelIndicator != null)
                    soundLevelIndicator.addHierarchyListener(this);
            }
        }

        /**
         * Sets the new capture device used by the audio level indicator.
         *
         * @param deviceSession The new capture device used by the audio level
         * indicator.
         */
        private void setDeviceSession(AudioMediaDeviceSession deviceSession)
        {
            if (this.deviceSession == deviceSession)
                return;

            if (this.deviceSession != null)
            {
                try
                {
                    this.deviceSession.close();
                }
                finally
                {
                    this.deviceSession.setLocalUserAudioLevelListener(null);
                    soundLevelIndicator.resetSoundLevel();
                }
            }

            this.deviceSession = deviceSession;

            if (deviceSession != null)
            {
                deviceSession.setContentDescriptor(
                        new ContentDescriptor(ContentDescriptor.RAW));
                deviceSession.setLocalUserAudioLevelListener(
                        audioLevelListener);

                deviceSession.start(MediaDirection.SENDONLY);

                try
                {
                    DataSource dataSource = deviceSession.getOutputDataSource();

                    dataSource.connect();

                    PushBufferStream[] streams
                        = ((PushBufferDataSource) dataSource).getStreams();

                    for (PushBufferStream stream : streams)
                        stream.setTransferHandler(transferHandler);

                    dataSource.start();
                }
                catch (Throwable t)
                {
                    if (t instanceof ThreadDeath)
                        throw (ThreadDeath) t;
                }
            }
        }
    }

    /**
     * Renders the available resolutions in the combo box.
     */
    private static class ResolutionCellRenderer
        extends DefaultListCellRenderer
    {
        /**
         * The serialization version number of the
         * <tt>ResolutionCellRenderer</tt> class. Defined to the value of
         * <tt>0</tt> because the <tt>ResolutionCellRenderer</tt> instances do
         * not have state of their own.
         */
        private static final long serialVersionUID = 0L;

        /**
         * Sets readable text describing the resolution if the selected
         * value is null we return the string "Auto".
         *
         * @param list
         * @param value
         * @param index
         * @param isSelected
         * @param cellHasFocus
         * @return Component
         */
        @Override
        public Component getListCellRendererComponent(
            JList list,
            Object value,
            int index,
            boolean isSelected,
            boolean cellHasFocus)
        {
            // call super to set backgrounds and fonts
            super.getListCellRendererComponent(
                    list,
                    value,
                    index,
                    isSelected,
                    cellHasFocus);

            // now just change the text
            if(value == null)
                setText("Auto");
            else if(value instanceof Dimension)
            {
                Dimension d = (Dimension)value;

                setText(((int) d.getWidth()) + "x" + ((int) d.getHeight()));
            }
            return this;
        }
    }

    /**
     * Wrapper for the device list field.
     */
    private static class DeviceComboBoxField
    {
        /**
         * The combo box with the devices.
         */
        private JComboBox deviceComboBox = null;

        /**
         * The <tt>JList</tt> with the devices.
         */
        private JList deviceList = null;

        /**
         * The current component that displays the list with the devices.
         */
        private Component deviceComponent;

        /**
         * The listener for the field.
         */
        private Listener listener;

        /**
         * Model for the field.
         */
        final DeviceConfigurationComboBoxModel model;

        /**
         * Constructs <tt>DeviceComboBoxField</tt> instance.
         * @param type the type of the configuration panel
         * @param devicePanel the container of the field.
         */
        public DeviceComboBoxField(final int type, Container devicePanel)
        {
            model = new DeviceConfigurationComboBoxModel(
                mediaService.getDeviceConfiguration(),
                type);

            if(!OSUtils.IS_WINDOWS
                || type != DeviceConfigurationComboBoxModel.VIDEO)
            {
                deviceComboBox = new JComboBox();
                deviceComboBox.setEditable(false);
                deviceComboBox.setModel(model);
                devicePanel.add(deviceComboBox);
                deviceComponent = deviceComboBox;
            }
            else
            {
                deviceList = new JList();
                deviceList.setModel(model);
                JScrollPane listScroller = new JScrollPane(deviceList);
                listScroller.setPreferredSize(new Dimension(200, 38));
                deviceList.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
                deviceList.setLayoutOrientation(JList.VERTICAL);
                deviceList.setVisibleRowCount(-1);
                deviceList.setSelectedValue(model.getSelectedItem(), true);
                devicePanel.add(listScroller);
                deviceComponent = deviceList;
            }
        }

        /**
         * Returns the field component
         * @return the field component
         */
        public Component getComponent()
        {
            return deviceComponent;
        }

        /**
         * Returns the selected device
         * @return the selected device
         */
        public Object getSelectedItem()
        {
            return (deviceComboBox != null)?
                deviceComboBox.getSelectedItem() : deviceList.getSelectedValue();
        }

        /**
         * Adds a listener to the field.
         * @param listener the listener to be added.
         */
        public void addListener(final Listener listener)
        {
            this.listener = listener;
            if(deviceComboBox != null)
            {
                deviceComboBox.addActionListener(new ActionListener()
                {

                    @Override
                    public void actionPerformed(ActionEvent e)
                    {
                        listener.onAction();
                    }
                });
            }
            else
            {
                deviceList.addListSelectionListener(new ListSelectionListener()
                {

                    @Override
                    public void valueChanged(ListSelectionEvent e)
                    {
                        model.setSelectedItem(deviceList.getSelectedValue());
                        listener.onAction();
                    }
                });
            }
        }

        /**
         * Interface for the listener attached to the field.
         */
        public static interface Listener
        {
            public void onAction();
        }
    }

    /**
     * Indicates if the Devices settings configuration tab
     * should be disabled, i.e. not visible to the user.
     */
    private static final String DEVICES_DISABLED_PROP
        = "net.java.sip.communicator.impl.neomedia.devicesconfig.DISABLED";

    /**
     * Indicates if the Audio/Video encodings configuration tab
     * should be disabled, i.e. not visible to the user.
     */
    private static final String ENCODINGS_DISABLED_PROP
        = "net.java.sip.communicator.impl.neomedia.encodingsconfig.DISABLED";

    /**
     * The <tt>Logger</tt> used by the <tt>MediaConfigurationServiceImpl</tt>
     * class for logging output.
     */
    private static final Logger logger
        = Logger.getLogger(MediaConfigurationImpl.class);

    /**
     * The <tt>MediaService</tt> implementation used by
     * <tt>MediaConfigurationImpl</tt>.
     */
    private static final MediaServiceImpl mediaService
        = NeomediaActivator.getMediaServiceImpl();

    /**
     * The name of the sound file used to test the playback and the notification
     * devices.
     */
    private static final String TEST_SOUND_FILENAME_PROP
        = "net.java.sip.communicator.impl.neomedia.TestSoundFilename";

    /**
     * Indicates if the Video/More Settings configuration tab
     * should be disabled, i.e. not visible to the user.
     */
    private static final String VIDEO_MORE_SETTINGS_DISABLED_PROP
        = "net.java.sip.communicator.impl.neomedia.videomoresettingsconfig.DISABLED";

    /**
     * The preferred width of all panels.
     */
    private final static int WIDTH = 350;

    /**
     * Creates the video advanced settings.
     *
     * @return video advanced settings panel.
     */
    private static Component createVideoAdvancedSettings()
    {
        ResourceManagementService resources = NeomediaActivator.getResources();

        final DeviceConfiguration deviceConfig =
            mediaService.getDeviceConfiguration();

        TransparentPanel centerPanel =
            new TransparentPanel(new GridBagLayout());
        centerPanel.setMaximumSize(new Dimension(WIDTH, 150));

        JButton resetDefaultsButton = new JButton(
            resources.getI18NString(
                    "impl.media.configform.VIDEO_RESET"));
        JPanel resetButtonPanel = new TransparentPanel(
                new FlowLayout(FlowLayout.RIGHT));
        resetButtonPanel.add(resetDefaultsButton);

        final JPanel centerAdvancedPanel
            = new TransparentPanel(new BorderLayout());
        centerAdvancedPanel.add(centerPanel, BorderLayout.NORTH);
        centerAdvancedPanel.add(resetButtonPanel, BorderLayout.SOUTH);

        GridBagConstraints constraints = new GridBagConstraints();
        constraints.fill = GridBagConstraints.HORIZONTAL;
        constraints.anchor = GridBagConstraints.NORTHWEST;
        constraints.insets = new Insets(5, 5, 0, 0);
        constraints.gridx = 0;
        constraints.weightx = 0;
        constraints.weighty = 0;
        constraints.gridy = 0;

        centerPanel.add(new JLabel(
            resources.getI18NString("impl.media.configform.VIDEO_RESOLUTION")),
            constraints);
        constraints.gridy = 1;
        constraints.insets = new Insets(0, 0, 0, 0);
        final JCheckBox frameRateCheck = new SIPCommCheckBox(
            resources.getI18NString("impl.media.configform.VIDEO_FRAME_RATE"));
        centerPanel.add(frameRateCheck, constraints);
        constraints.gridy = 2;
        constraints.insets = new Insets(5, 5, 0, 0);
        centerPanel.add(new JLabel(
            resources.getI18NString(
                    "impl.media.configform.VIDEO_PACKETS_POLICY")),
            constraints);
        constraints.gridy = 3;
        centerPanel.add(new JLabel(
            resources.getI18NString(
                    "impl.media.configform.VIDEO_BITRATE")),
            constraints);

        constraints.weightx = 1;
        constraints.gridx = 1;
        constraints.gridy = 0;
        constraints.insets = new Insets(5, 0, 0, 5);
        Object[] resolutionValues
            = new Object[DeviceConfiguration.SUPPORTED_RESOLUTIONS.length + 1];
        System.arraycopy(DeviceConfiguration.SUPPORTED_RESOLUTIONS, 0,
                        resolutionValues, 1,
                        DeviceConfiguration.SUPPORTED_RESOLUTIONS.length);
        final JComboBox sizeCombo = new JComboBox(resolutionValues);
        sizeCombo.setRenderer(new ResolutionCellRenderer());
        sizeCombo.setEditable(false);
        centerPanel.add(sizeCombo, constraints);

        // default value is 20
        final JSpinner frameRate = new JSpinner(new SpinnerNumberModel(
            20, 5, 30, 1));
        frameRate.addChangeListener(new ChangeListener()
        {
            public void stateChanged(ChangeEvent e)
            {
                deviceConfig.setFrameRate(
                        ((SpinnerNumberModel)frameRate.getModel())
                            .getNumber().intValue());
            }
        });
        constraints.gridy = 1;
        constraints.insets = new Insets(0, 0, 0, 5);
        centerPanel.add(frameRate, constraints);

        frameRateCheck.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent e)
            {
                if(frameRateCheck.isSelected())
                {
                    deviceConfig.setFrameRate(
                        ((SpinnerNumberModel)frameRate.getModel())
                            .getNumber().intValue());
                }
                else // unlimited framerate
                    deviceConfig.setFrameRate(-1);

                frameRate.setEnabled(frameRateCheck.isSelected());
            }
        });

        int videoMaxBandwith = deviceConfig.getVideoRTPPacingThreshold();
        // Accord the current value with the maximum allowed value. Fixes
        // existing configurations that have been set to a number larger than
        // the advised maximum value.
        videoMaxBandwith = ((videoMaxBandwith > 999) ? 999 : videoMaxBandwith);

        final JSpinner videoMaxBandwidth = new JSpinner(new SpinnerNumberModel(
            videoMaxBandwith,
            1, 999, 1));
        videoMaxBandwidth.addChangeListener(new ChangeListener()
        {
            public void stateChanged(ChangeEvent e)
            {
                deviceConfig.setVideoRTPPacingThreshold(
                        ((SpinnerNumberModel) videoMaxBandwidth.getModel())
                                .getNumber().intValue());
            }
        });
        constraints.gridx = 1;
        constraints.gridy = 2;
        constraints.insets = new Insets(0, 0, 5, 5);
        centerPanel.add(videoMaxBandwidth, constraints);

        final JSpinner videoBitrate = new JSpinner(new SpinnerNumberModel(
            deviceConfig.getVideoBitrate(),
            1, Integer.MAX_VALUE, 1));
        videoBitrate.addChangeListener(new ChangeListener()
        {
            public void stateChanged(ChangeEvent e)
            {
                deviceConfig.setVideoBitrate(
                        ((SpinnerNumberModel) videoBitrate.getModel())
                                .getNumber().intValue());
            }
        });
        constraints.gridy = 3;
        centerPanel.add(videoBitrate, constraints);

        resetDefaultsButton.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent e)
            {
                // reset to defaults
                sizeCombo.setSelectedIndex(0);
                frameRateCheck.setSelected(false);
                frameRate.setEnabled(false);
                frameRate.setValue(20);
                // unlimited framerate
                deviceConfig.setFrameRate(-1);
                videoMaxBandwidth.setValue(
                        DeviceConfiguration.DEFAULT_VIDEO_RTP_PACING_THRESHOLD);
                videoBitrate.setValue(
                        DeviceConfiguration.DEFAULT_VIDEO_BITRATE);
            }
        });

        // load selected value or auto
        Dimension videoSize = deviceConfig.getVideoSize();

        if((videoSize.getHeight() != DeviceConfiguration.DEFAULT_VIDEO_HEIGHT)
                && (videoSize.getWidth()
                        != DeviceConfiguration.DEFAULT_VIDEO_WIDTH))
            sizeCombo.setSelectedItem(deviceConfig.getVideoSize());
        else
            sizeCombo.setSelectedIndex(0);
        sizeCombo.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent e)
            {
                Dimension selectedVideoSize
                    = (Dimension) sizeCombo.getSelectedItem();

                if(selectedVideoSize == null)
                {
                    // the auto value, default one
                    selectedVideoSize
                        = new Dimension(
                                DeviceConfiguration.DEFAULT_VIDEO_WIDTH,
                                DeviceConfiguration.DEFAULT_VIDEO_HEIGHT);
                }
                deviceConfig.setVideoSize(selectedVideoSize);
            }
        });

        frameRateCheck.setSelected(
            deviceConfig.getFrameRate()
                != DeviceConfiguration.DEFAULT_VIDEO_FRAMERATE);
        frameRate.setEnabled(frameRateCheck.isSelected());

        if(frameRate.isEnabled())
            frameRate.setValue(deviceConfig.getFrameRate());

        return centerAdvancedPanel;
    }

    /**
     * Creates the video container.
     * @param noVideoComponent the container component.
     * @return the video container.
     */
    private static JComponent createVideoContainer(Component noVideoComponent)
    {
        return new VideoContainer(noVideoComponent, false);
    }

    /**
     * Creates preview for the (video) device in the video container.
     *
     * @param device the device
     * @param videoContainer the video container
     * @throws IOException a problem accessing the device
     * @throws MediaException a problem getting preview
     */
    private static void createVideoPreview(
            CaptureDeviceInfo device,
            JComponent videoContainer)
        throws IOException,
               MediaException
    {
        videoContainer.removeAll();

        videoContainer.revalidate();
        videoContainer.repaint();

        if (device == null)
            return;

        for (MediaDevice mediaDevice
                : mediaService.getDevices(MediaType.VIDEO, MediaUseCase.ANY))
        {
            if(((MediaDeviceImpl) mediaDevice).getCaptureDeviceInfo().equals(
                    device))
            {
                Dimension videoContainerSize
                    = videoContainer.getPreferredSize();
                Component preview
                    = (Component)
                        mediaService.getVideoPreviewComponent(
                                mediaDevice,
                                videoContainerSize.width,
                                videoContainerSize.height);

                if (preview != null)
                    videoContainer.add(preview);
                break;
            }
        }
    }

    /**
     * The mnemonic for a type.
     * @param type audio or video type.
     * @return the mnemonic.
     */
    private static char getDisplayedMnemonic(int type)
    {
        switch (type)
        {
        case DeviceConfigurationComboBoxModel.AUDIO:
            return NeomediaActivator.getResources().getI18nMnemonic(
                "impl.media.configform.AUDIO");
        case DeviceConfigurationComboBoxModel.VIDEO:
            return NeomediaActivator.getResources().getI18nMnemonic(
                "impl.media.configform.VIDEO");
        default:
            throw new IllegalArgumentException("type");
        }
    }

    /**
     * A label for a type.
     * @param type the type.
     * @return the label.
     */
    private static String getLabelText(int type)
    {
        switch (type)
        {
        case DeviceConfigurationComboBoxModel.AUDIO:
            return NeomediaActivator.getResources().getI18NString(
                "impl.media.configform.AUDIO");
        case DeviceConfigurationComboBoxModel.AUDIO_CAPTURE:
            return NeomediaActivator.getResources().getI18NString(
                "impl.media.configform.AUDIO_IN");
        case DeviceConfigurationComboBoxModel.AUDIO_NOTIFY:
            return NeomediaActivator.getResources().getI18NString(
                "impl.media.configform.AUDIO_NOTIFY");
        case DeviceConfigurationComboBoxModel.AUDIO_PLAYBACK:
            return NeomediaActivator.getResources().getI18NString(
                "impl.media.configform.AUDIO_OUT");
        case DeviceConfigurationComboBoxModel.VIDEO:
            return NeomediaActivator.getResources().getI18NString(
                "impl.media.configform.VIDEO");
        default:
            throw new IllegalArgumentException("type");
        }
    }

    /**
     * Used to move encoding options.
     *
     * @param table the table with encodings
     * @param up move direction.
     */
    private static void move(JTable table, boolean up)
    {
        int index
            = ((EncodingConfigurationTableModel) table.getModel()).move(
                    table.getSelectedRow(),
                    up);

        table.getSelectionModel().setSelectionInterval(index, index);
    }

    /**
     * The thread which updates the capture device as selected by the user. This
     * prevent the UI to lock while changing the device.
     */
    private AudioLevelListenerThread audioLevelListenerThread = null;

    /**
     * The button used to play a sound in order to test notification devices.
     */
    private JButton notificationPlaySoundButton;

    /**
     * The combo box used to selected the notification device.
     */
    private JComboBox notifyCombo;

    /**
     * The combo box used to selected the playback device.
     */
    private JComboBox playbackCombo;

    /**
     * The button used to play a sound in order to test playback device.
     */
    private JButton playbackPlaySoundButton;

    /**
     * Indicates that one of the contained in this panel buttons has been
     * clicked.
     * @param e the <tt>ActionEvent</tt> that notified us
     */
    public void actionPerformed(ActionEvent e)
    {
        boolean isPlaybackEvent = (e.getSource() == playbackPlaySoundButton);

        // If the user clicked on one pley sound button.
        if(isPlaybackEvent
                || e.getSource() == notificationPlaySoundButton)
        {
            AudioNotifierService audioNotifServ
                = NeomediaActivator.getAudioNotifierService();
            String testSoundFilename
                = NeomediaActivator.getConfigurationService()
                    .getString(
                            TEST_SOUND_FILENAME_PROP,
                            NeomediaActivator.getResources().getSoundPath(
                                "TEST_SOUND")
                            );
            SCAudioClip sound = audioNotifServ.createAudio(
                    testSoundFilename,
                    isPlaybackEvent);
            sound.play();
        }
        // If the selected item of the playback or notify combobox has changed.
        else if(e.getSource() == playbackCombo
                || e.getSource() == notifyCombo)
        {
            DeviceConfigurationComboBoxModel.CaptureDevice device
                = (DeviceConfigurationComboBoxModel.CaptureDevice)
                    ((JComboBox) e.getSource()).getSelectedItem();

            boolean isEnabled = (device.info != null);
            if(e.getSource() == playbackCombo)
            {
                playbackPlaySoundButton.setEnabled(isEnabled);
            }
            else
            {
                notificationPlaySoundButton.setEnabled(isEnabled);
            }
        }
    }

    /**
     * Returns the audio configuration panel.
     *
     * @return the audio configuration panel
     */
    public Component createAudioConfigPanel()
    {
        return createControls(DeviceConfigurationComboBoxModel.AUDIO);
    }

    /**
     * Creates the UI controls which are to control the details of a specific
     * <tt>AudioSystem</tt>.
     *
     * @param audioSystem the <tt>AudioSystem</tt> for which the UI controls to
     * control its details are to be created
     * @param container the <tt>JComponent</tt> into which the UI controls which
     * are to control the details of the specified <tt>audioSystem</tt> are to
     * be added
     */
    public void createAudioSystemControls(
            final AudioSystem audioSystem,
            JComponent container)
    {
        GridBagConstraints cnstrnts = new GridBagConstraints();

        cnstrnts.anchor = GridBagConstraints.NORTHWEST;
        cnstrnts.fill = GridBagConstraints.HORIZONTAL;
        cnstrnts.weighty = 0;

        int audioSystemFeatures = audioSystem.getFeatures();
        boolean featureNotifyAndPlaybackDevices
            = ((audioSystemFeatures
                    & AudioSystem.FEATURE_NOTIFY_AND_PLAYBACK_DEVICES)
                != 0);

        cnstrnts.gridx = 0;
        cnstrnts.insets = new Insets(3, 0, 3, 3);
        cnstrnts.weightx = 0;

        cnstrnts.gridy = 0;
        container.add(new JLabel(getLabelText(
            DeviceConfigurationComboBoxModel.AUDIO_CAPTURE)), cnstrnts);
        if (featureNotifyAndPlaybackDevices)
        {
            cnstrnts.gridy = 2;
            container.add(new JLabel(getLabelText(
                DeviceConfigurationComboBoxModel.AUDIO_PLAYBACK)), cnstrnts);
            cnstrnts.gridy = 3;
            container.add(new JLabel(getLabelText(
                DeviceConfigurationComboBoxModel.AUDIO_NOTIFY)), cnstrnts);
        }

        cnstrnts.gridx = 1;
        cnstrnts.insets = new Insets(3, 3, 3, 0);
        cnstrnts.weightx = 1;

        JComboBox captureCombo = null;

        if (featureNotifyAndPlaybackDevices)
        {
            captureCombo = new JComboBox();
            captureCombo.setEditable(false);
            captureCombo.setModel(
                    new DeviceConfigurationComboBoxModel(
                            mediaService.getDeviceConfiguration(),
                            DeviceConfigurationComboBoxModel.AUDIO_CAPTURE));
            cnstrnts.gridy = 0;
            container.add(captureCombo, cnstrnts);
        }

        int anchor = cnstrnts.anchor;
        SoundLevelIndicator capturePreview
            = new SoundLevelIndicator(
                    SimpleAudioLevelListener.MIN_LEVEL,
                    SimpleAudioLevelListener.MAX_LEVEL);

        cnstrnts.anchor = GridBagConstraints.CENTER;
        cnstrnts.gridy = (captureCombo == null) ? 0 : 1;
        container.add(capturePreview, cnstrnts);
        cnstrnts.anchor = anchor;

        cnstrnts.gridy = GridBagConstraints.RELATIVE;

        if (featureNotifyAndPlaybackDevices)
        {
            playbackCombo = new JComboBox();
            playbackCombo.setEditable(false);
            playbackCombo.setModel(
                    new DeviceConfigurationComboBoxModel(
                            mediaService.getDeviceConfiguration(),
                            DeviceConfigurationComboBoxModel.AUDIO_PLAYBACK));
            playbackCombo.addActionListener(this);
            container.add(playbackCombo, cnstrnts);

            notifyCombo = new JComboBox();
            notifyCombo.setEditable(false);
            notifyCombo.setModel(
                    new DeviceConfigurationComboBoxModel(
                            mediaService.getDeviceConfiguration(),
                            DeviceConfigurationComboBoxModel.AUDIO_NOTIFY));
            notifyCombo.addActionListener(this);
            container.add(notifyCombo, cnstrnts);
        }

        int[] checkBoxAudioSystemFeatures
            = new int[]
                    {
                        AudioSystem.FEATURE_ECHO_CANCELLATION,
                        AudioSystem.FEATURE_DENOISE,
                        AudioSystem.FEATURE_AGC
                    };

        for (int i = 0; i < checkBoxAudioSystemFeatures.length; i++)
        {
            final int f = checkBoxAudioSystemFeatures[i];

            if ((f & audioSystemFeatures) != 0)
            {
                String textKey;
                boolean selected;

                switch (f)
                {
                case AudioSystem.FEATURE_AGC:
                    textKey = "impl.media.configform.AUTOMATICGAINCONTROL";
                    selected = audioSystem.isAutomaticGainControl();
                    break;
                case AudioSystem.FEATURE_DENOISE:
                    textKey = "impl.media.configform.DENOISE";
                    selected = audioSystem.isDenoise();
                    break;
                case AudioSystem.FEATURE_ECHO_CANCELLATION:
                    textKey = "impl.media.configform.ECHOCANCEL";
                    selected = audioSystem.isEchoCancel();
                    break;
                default:
                    continue;
                }

                final SIPCommCheckBox checkBox
                    = new SIPCommCheckBox(
                            NeomediaActivator.getResources().getI18NString(
                                    textKey));

                /*
                 * First set the selected one, then add the listener in order to
                 * avoid saving the value when using the default one and only
                 * showing to user without modification.
                 */
                checkBox.setSelected(selected);
                checkBox.addItemListener(
                        new ItemListener()
                        {
                            public void itemStateChanged(ItemEvent e)
                            {
                                boolean b = checkBox.isSelected();

                                switch (f)
                                {
                                case AudioSystem.FEATURE_AGC:
                                    audioSystem.setAutomaticGainControl(b);
                                    break;
                                case AudioSystem.FEATURE_DENOISE:
                                    audioSystem.setDenoise(b);
                                    break;
                                case AudioSystem.FEATURE_ECHO_CANCELLATION:
                                    audioSystem.setEchoCancel(b);
                                    break;
                                }
                            }
                        });
                container.add(checkBox, cnstrnts);
            }
        }

        // Adds the play buttons for testing playback and notification devices.
        cnstrnts.gridx = 2;
        cnstrnts.insets = new Insets(3, 3, 3, 0);
        cnstrnts.weightx = 0;

        if (featureNotifyAndPlaybackDevices)
        {
            // Playback play sound button.
            cnstrnts.gridy = 2;
            playbackPlaySoundButton
                = new JButton(new ImageIcon(NeomediaActivator.getResources()
                            .getImageInBytes(
                                "plugin.notificationconfig.PLAY_ICON")));
            playbackPlaySoundButton.setMinimumSize(new Dimension(30,30));
            playbackPlaySoundButton.setPreferredSize(new Dimension(30,30));
            if(((DeviceConfigurationComboBoxModel.CaptureDevice)
                        playbackCombo.getSelectedItem()).info == null)
            {
                playbackPlaySoundButton.setEnabled(false);
            }
            playbackPlaySoundButton.setOpaque(false);
            playbackPlaySoundButton.addActionListener(this);
            container.add(playbackPlaySoundButton, cnstrnts);

            // Notification play sound button.
            cnstrnts.gridy = 3;
            notificationPlaySoundButton
                = new JButton(new ImageIcon(NeomediaActivator.getResources()
                            .getImageInBytes(
                                "plugin.notificationconfig.PLAY_ICON")));
            notificationPlaySoundButton.setMinimumSize(new Dimension(30,30));
            notificationPlaySoundButton.setPreferredSize(new Dimension(30,30));
            if(((DeviceConfigurationComboBoxModel.CaptureDevice)
                        notifyCombo.getSelectedItem()).info == null)
            {
                notificationPlaySoundButton.setEnabled(false);
            }
            notificationPlaySoundButton.setOpaque(false);
            notificationPlaySoundButton.addActionListener(this);
            container.add(notificationPlaySoundButton, cnstrnts);
        }

        if (audioLevelListenerThread == null)
        {
            audioLevelListenerThread
                = new AudioLevelListenerThread(
                        audioSystem,
                        captureCombo,
                        capturePreview);
        }
        else
        {
            audioLevelListenerThread.init(
                    audioSystem,
                    captureCombo,
                    capturePreview);
        }
    }

    /**
     * Creates basic controls for a type (AUDIO or VIDEO).
     *
     * @param type the type.
     * @return the build Component.
     */
    private Component createBasicControls(final int type)
    {
        final boolean setAudioSystemIsDisabled
            = (type == DeviceConfigurationComboBoxModel.AUDIO)
                && NeomediaActivator.getConfigurationService().getBoolean(
                        MediaServiceImpl.DISABLE_SET_AUDIO_SYSTEM_PNAME,
                        false);
        final DeviceComboBoxField deviceComboBox;
        final Container devicePanel;

        if (setAudioSystemIsDisabled)
        {
            deviceComboBox = null;
            devicePanel = null;
        }
        else
        {
            JLabel deviceLabel = new JLabel(getLabelText(type));

            deviceLabel.setDisplayedMnemonic(getDisplayedMnemonic(type));

            devicePanel
                = new TransparentPanel(new FlowLayout(FlowLayout.CENTER));
            devicePanel.setMaximumSize(new Dimension(WIDTH, 25));
            devicePanel.add(deviceLabel);

            deviceComboBox = new DeviceComboBoxField(type, devicePanel);
            deviceLabel.setLabelFor(deviceComboBox.getComponent());
        }

        final JPanel deviceAndPreviewPanel
            = new TransparentPanel(new BorderLayout());
        int preferredDeviceAndPreviewPanelHeight;

        switch (type)
        {
        case DeviceConfigurationComboBoxModel.AUDIO:
            preferredDeviceAndPreviewPanelHeight
                = (devicePanel == null) ? 200 : 245;
            break;
        case DeviceConfigurationComboBoxModel.VIDEO:
            preferredDeviceAndPreviewPanelHeight = 305;
            break;
        default:
            preferredDeviceAndPreviewPanelHeight = 0;
            break;
        }
        if (preferredDeviceAndPreviewPanelHeight > 0)
        {
            deviceAndPreviewPanel.setPreferredSize(
                    new Dimension(WIDTH, preferredDeviceAndPreviewPanelHeight));
        }
        if (devicePanel != null)
            deviceAndPreviewPanel.add(devicePanel, BorderLayout.NORTH);

        final DeviceComboBoxField.Listener deviceComboBoxActionListener
            = new DeviceComboBoxField.Listener()
            {
                public void onAction()
                {
                    boolean revalidateAndRepaint = false;

                    for (int i = deviceAndPreviewPanel.getComponentCount() - 1;
                            i >= 0;
                            i--)
                    {
                        Component c = deviceAndPreviewPanel.getComponent(i);

                        if (c != devicePanel)
                        {
                            deviceAndPreviewPanel.remove(i);
                            revalidateAndRepaint = true;
                        }
                    }

                    Component preview = null;

                    if ((deviceComboBox == null)
                            || ((deviceComboBox.getSelectedItem() != null)
                                    && deviceComboBox.getComponent().isShowing()))
                    {
                        preview
                            = createPreview(
                                    type,
                                    deviceComboBox,
                                    deviceAndPreviewPanel.getPreferredSize());
                    }

                    if (preview != null)
                    {
                        deviceAndPreviewPanel.add(preview, BorderLayout.CENTER);
                        revalidateAndRepaint = true;
                    }

                    if (revalidateAndRepaint)
                    {
                        deviceAndPreviewPanel.revalidate();
                        deviceAndPreviewPanel.repaint();
                    }
                }

            };

        if (deviceComboBox != null)
            deviceComboBox.addListener(deviceComboBoxActionListener);

        /*
         * We have to initialize the controls to reflect the configuration at
         * the time of creating this instance. Additionally, because the
         * preview will stop when it and its associated controls become
         * unnecessary, we have to restart it when the mentioned controls become
         * necessary again. We'll address the two goals described by pretending
         * there's a selection in the combo box when user interface becomes
         * displayable.
         */
        deviceAndPreviewPanel.addHierarchyListener(
                new HierarchyListener()
                {
                    public void hierarchyChanged(HierarchyEvent event)
                    {
                        if ((event.getChangeFlags()
                                    & HierarchyEvent.SHOWING_CHANGED)
                                != 0)
                        {
                            SwingUtilities.invokeLater(
                                    new Runnable()
                                    {
                                        public void run()
                                        {
                                            deviceComboBoxActionListener
                                                .onAction();
                                        }
                                    });
                        }
                    }
                });

        return deviceAndPreviewPanel;
    }

    /**
     * Creates all the controls (including encoding) for a type(AUDIO or VIDEO)
     *
     * @param type the type.
     * @return the build Component.
     */
    private Component createControls(int type)
    {
        ConfigurationService cfg = NeomediaActivator.getConfigurationService();

        Component devicesComponent = null;
        Component encodingsComponent = null;
        Component videoComponent = null;

        int compCount = 0;

        if (cfg == null || !cfg.getBoolean(DEVICES_DISABLED_PROP, false))
        {
            compCount++;
            devicesComponent = createBasicControls(type);
        }
        if (cfg == null || !cfg.getBoolean(ENCODINGS_DISABLED_PROP, false))
        {
            compCount++;
            encodingsComponent = createEncodingControls(type, null);
        }
        if ((type == DeviceConfigurationComboBoxModel.VIDEO)
                && ((cfg == null)
                    || !cfg.getBoolean(
                            VIDEO_MORE_SETTINGS_DISABLED_PROP,
                            false)))
        {
            compCount++;
            videoComponent = createVideoAdvancedSettings();
        }

        ResourceManagementService res = NeomediaActivator.getResources();
        Container container;

        // If we only have one configuration form we don't need to create a
        // tabbed pane.
        if (compCount < 2)
        {
            container = new TransparentPanel(new BorderLayout());

            if (devicesComponent != null)
                container.add(devicesComponent);
            else if (encodingsComponent != null)
                container.add(encodingsComponent);
            else if (videoComponent != null)
                container.add(videoComponent);
        }
        else
        {
            container = new SIPCommTabbedPane();

            SIPCommTabbedPane tabbedPane = (SIPCommTabbedPane) container;
            int index = 0;

            if (devicesComponent != null)
            {
                tabbedPane.insertTab(
                        res.getI18NString("impl.media.configform.DEVICES"),
                        null,
                        devicesComponent,
                        null,
                        index);
                index = 1;
            }
            if (encodingsComponent != null)
            {
                if (tabbedPane.getTabCount() >= 1)
                    index = 1;
                tabbedPane.insertTab(
                        res.getI18NString("impl.media.configform.ENCODINGS"),
                        null,
                        encodingsComponent,
                        null,
                        index);
            }
            if (videoComponent != null)
            {
                if (tabbedPane.getTabCount() >= 2)
                    index = 2;
                tabbedPane.insertTab(
                        res.getI18NString(
                            "impl.media.configform.VIDEO_MORE_SETTINGS"),
                        null,
                        videoComponent,
                        null,
                        index);
            }
        }

        return container;
    }

    /**
     * Creates Component for the encodings of type(AUDIO or VIDEO).
     *
     * @param type the type, either DeviceConfigurationComboBoxModel.AUDIO or
     * DeviceConfigurationComboBoxModel.AUDIO
     * @param encodingConfiguration The <tt>EncodingConfiguration</tt> instance
     * to use. If null, it will use the current encoding configuration from
     * the media service.
     * @return the component.
     */
    private Component createEncodingControls(int type,
            EncodingConfiguration encodingConfiguration)
    {
        if(encodingConfiguration == null)
        {
            encodingConfiguration
                    = mediaService.getCurrentEncodingConfiguration();
        }

        ResourceManagementService resources = NeomediaActivator.getResources();
        String key;

        final JTable table = new JTable();
        table.setShowGrid(false);
        table.setTableHeader(null);
        table.setDefaultRenderer(Object.class, new DefaultTableCellRenderer()
        {
            @Override
            public Component getTableCellRendererComponent(JTable rtable,
                Object value, boolean isSelected, boolean hasFocus, int row,
                int column)
            {
                Component component = super.getTableCellRendererComponent(
                    rtable, value, isSelected, hasFocus, row, column);
                component.setEnabled(rtable != null && rtable.isEnabled());
                return component;
            }
        });

        key = "impl.media.configform.UP";
        final JButton upButton = new JButton(resources.getI18NString(key));
        upButton.setMnemonic(resources.getI18nMnemonic(key));
        upButton.setOpaque(false);

        key = "impl.media.configform.DOWN";
        final JButton downButton = new JButton(resources.getI18NString(key));
        downButton.setMnemonic(resources.getI18nMnemonic(key));
        downButton.setOpaque(false);

        Container buttonBar = new TransparentPanel(new GridLayout(0, 1));
        buttonBar.add(upButton);
        buttonBar.add(downButton);

        Container parentButtonBar = new TransparentPanel(new BorderLayout());
        parentButtonBar.add(buttonBar, BorderLayout.NORTH);

        table.setModel(new EncodingConfigurationTableModel(type,
                encodingConfiguration));
        /*
         * The first column contains the check boxes which enable/disable their
         * associated encodings and it doesn't make sense to make it wider than
         * the check boxes.
         */
        TableColumnModel tableColumnModel = table.getColumnModel();
        TableColumn tableColumn = tableColumnModel.getColumn(0);
        tableColumn.setMaxWidth(tableColumn.getMinWidth());

        final ListSelectionListener tableSelectionListener =
            new ListSelectionListener()
            {
                public void valueChanged(ListSelectionEvent event)
                {
                    if (table.getSelectedRowCount() == 1)
                    {
                        int selectedRow = table.getSelectedRow();
                        if (selectedRow > -1)
                        {
                            upButton.setEnabled(selectedRow > 0);
                            downButton.setEnabled(selectedRow < (table
                                .getRowCount() - 1));
                            return;
                        }
                    }
                    upButton.setEnabled(false);
                    downButton.setEnabled(false);
                }
            };
        table.getSelectionModel().addListSelectionListener(
            tableSelectionListener);
        tableSelectionListener.valueChanged(null);

        ActionListener buttonListener = new ActionListener()
        {
            public void actionPerformed(ActionEvent event)
            {
                Object source = event.getSource();
                boolean up;
                if (source == upButton)
                    up = true;
                else if (source == downButton)
                    up = false;
                else
                    return;

                move(table, up);
            }
        };
        upButton.addActionListener(buttonListener);
        downButton.addActionListener(buttonListener);

        Container container = new TransparentPanel(new BorderLayout())
        {
            @Override
            public void setEnabled(boolean enabled)
            {
                super.setEnabled(enabled);
                table.setEnabled(enabled);
                if (enabled)
                {
                    tableSelectionListener.valueChanged(null);
                }
                else
                {
                    upButton.setEnabled(false);
                    downButton.setEnabled(false);
                }
            }
        };
        container.setPreferredSize(new Dimension(WIDTH, 100));
        container.setMaximumSize(new Dimension(WIDTH, 100));

        container.add(new JScrollPane(table), BorderLayout.CENTER);
        container.add(parentButtonBar, BorderLayout.EAST);
        return container;
    }

    /**
     * Returns a component for encodings configuration for the given
     * <tt>mediaType</tt>
     *
     * @param mediaType Either <tt>MediaType.AUDIO</tt> or
     * <tt>MediaType.VIDEO</tt>
     * @param encodingConfiguration The <tt>EncodingConfiguration</tt> instance
     * to use. If null, it will use the current encoding configuration from
     * the media service.
     * @return The component for encodings configuration.
     */
    public Component createEncodingControls(
            MediaType mediaType,
            EncodingConfiguration encodingConfiguration)
    {
        if(encodingConfiguration == null)
        {
            encodingConfiguration
                = mediaService.getCurrentEncodingConfiguration();
        }

        int deviceConfigurationComboBoxModelType;

        switch (mediaType)
        {
        case AUDIO:
            deviceConfigurationComboBoxModelType
                = DeviceConfigurationComboBoxModel.AUDIO;
            break;
        case VIDEO:
            deviceConfigurationComboBoxModelType
                = DeviceConfigurationComboBoxModel.VIDEO;
            break;
        default:
            throw new IllegalArgumentException("mediaType");
        }

        return
            createEncodingControls(
                    deviceConfigurationComboBoxModelType,
                    encodingConfiguration);
    }

    /**
     * Initializes a new <tt>Component</tt> which.is to preview and/or allow
     * detailed configuration of an audio or video <tt>DeviceSystem</tt>.
     *
     * @param type either {@link DeviceConfigurationComboBoxModel#AUDIO} or
     * {@link DeviceConfigurationComboBoxModel#VIDEO}
     * @param comboBox the <tt>JComboBox</tt> which lists the available
     * alternatives and the selection which is to be previewed. May be
     * <tt>null</tt> in the case of audio in which case it is assumed that the
     * user is not allowed to set the <tt>AudioSystem</tt> to be used and the
     * selection is determined by the <tt>DeviceConfiguration</tt> of the
     * <tt>MediaService</tt>.
     * @param prefSize the preferred size to be applied to the preview
     * @return a new <tt>Component</tt> which is to preview and/or allow
     * detailed configuration of the <tt>DeviceSystem</tt> identified by
     * <tt>type</tt> and <tt>comboBox</tt>
     */
    private Component createPreview(
            int type,
            DeviceComboBoxField comboBox,
            Dimension prefSize)
    {
        JComponent preview = null;

        if (type == DeviceConfigurationComboBoxModel.AUDIO)
        {
            AudioSystem audioSystem = null;

            /*
             * If the Audio System combo box is disabled (i.e. the user is not
             * allowed to set the AudioSystem to be used), the current
             * AudioSystem (specified by the DeviceConfiguration of the
             * MediaService) is to be configured.
             */
            if ((comboBox == null) || !comboBox.getComponent().isEnabled())
            {
                audioSystem
                    = mediaService.getDeviceConfiguration().getAudioSystem();
            }
            else
            {
                Object selectedItem = comboBox.getSelectedItem();

                if (selectedItem instanceof AudioSystem)
                {
                    audioSystem = (AudioSystem) selectedItem;

                    AudioSystem mediaServiceDeviceConfigurationAudioSystem
                        = mediaService
                            .getDeviceConfiguration()
                                .getAudioSystem();

                    if (audioSystem
                            != mediaServiceDeviceConfigurationAudioSystem)
                    {
                        logger.warn(
                                "JComboBox.selectedItem is not identical to"
                                    + " MediaService.deviceConfiguration.audioSystem!");
                    }
                }
            }

            if ((audioSystem != null)
                    && !NoneAudioSystem.LOCATOR_PROTOCOL.equalsIgnoreCase(
                            audioSystem.getLocatorProtocol()))
            {
                preview = new TransparentPanel(new GridBagLayout());
                createAudioSystemControls(audioSystem, preview);
            }
            else
            {
                /*
                 * If there are AudioSystems other than "None" and they have all
                 * not been reported as available, then each of them failed to
                 * detect any devices whatsoever.
                 */
                AudioSystem[] audioSystems = AudioSystem.getAudioSystems();

                if ((audioSystems != null) && (audioSystems.length != 1))
                {
                    AudioSystem[] availableAudioSystems
                        = mediaService
                            .getDeviceConfiguration()
                                .getAvailableAudioSystems();

                    if ((availableAudioSystems != null)
                            && (availableAudioSystems.length == 1))
                    {
                        String noAvailableAudioDevice
                            = NeomediaActivator.getResources().getI18NString(
                                    "impl.media.configform"
                                        + ".NO_AVAILABLE_AUDIO_DEVICE");

                        preview = new TransparentPanel(new GridBagLayout());
                        preview.add(new JLabel(noAvailableAudioDevice));
                    }
                }
            }
        }
        else if (type == DeviceConfigurationComboBoxModel.VIDEO)
        {
            JLabel noPreview
                = new JLabel(
                        NeomediaActivator.getResources().getI18NString(
                                "impl.media.configform.NO_PREVIEW"));

            noPreview.setHorizontalAlignment(SwingConstants.CENTER);
            noPreview.setVerticalAlignment(SwingConstants.CENTER);

            preview = createVideoContainer(noPreview);
            preview.setPreferredSize(prefSize);

            Object selectedItem = comboBox.getSelectedItem();
            CaptureDeviceInfo device = null;
            if (selectedItem
                    instanceof
                        DeviceConfigurationComboBoxModel.CaptureDevice)
                device
                    = ((DeviceConfigurationComboBoxModel.CaptureDevice)
                            selectedItem)
                        .info;

            Exception exception;
            try
            {
                createVideoPreview(device, preview);
                exception = null;
            }
            catch (IOException ex)
            {
                exception = ex;
            }
            catch (MediaException ex)
            {
                exception = ex;
            }
            if (exception != null)
            {
                logger.error(
                        "Failed to create preview for device " + device,
                        exception);
            }
        }

        return preview;
    }

    /**
     * Returns the video configuration panel.
     *
     * @return the video configuration panel
     */
    public Component createVideoConfigPanel()
    {
        return createControls(DeviceConfigurationComboBoxModel.VIDEO);
    }

    /**
     * Returns the <tt>MediaService</tt> instance.
     *
     * @return the <tt>MediaService</tt> instance
     */
    public MediaService getMediaService()
    {
        return mediaService;
    }
}