summaryrefslogtreecommitdiff
path: root/rakia/media-channel.c
blob: ef6db8597606032aab3a26672d036dbd4e624854 (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
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
/*
 * sip-media-channel.c - Source for RakiaMediaChannel
 * Copyright (C) 2005-2008 Collabora Ltd.
 * Copyright (C) 2005-2010 Nokia Corporation
 *   @author Kai Vehmanen <first.surname@nokia.com>
 *   @author Mikhail Zabaluev <mikhail.zabaluev@nokia.com>
 *
 * Based on telepathy-gabble implementation (gabble-media-channel).
 *   @author Ole Andre Vadla Ravnaas <ole.andre.ravnaas@collabora.co.uk>
 *
 * This work is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This work is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this work; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include "config.h"

#include "rakia/media-channel.h"

#include <stdlib.h>
#include <string.h>

#include <telepathy-glib/channel-iface.h>
#include <telepathy-glib/dbus.h>
#include <telepathy-glib/dtmf.h>
#include <telepathy-glib/errors.h>
#include <telepathy-glib/exportable-channel.h>
#include <telepathy-glib/interfaces.h>
#include <telepathy-glib/svc-channel.h>

#include <rakia/event-target.h>

#define DEBUG_FLAG RAKIA_DEBUG_MEDIA
#include "rakia/debug.h"

#include <rakia/media-session.h>
#include <rakia/base-connection.h>

#define RAKIA_CHANNEL_CALL_STATE_PROCEEDING_MASK \
    (TP_CHANNEL_CALL_STATE_RINGING | \
     TP_CHANNEL_CALL_STATE_QUEUED | \
     TP_CHANNEL_CALL_STATE_IN_PROGRESS)

/* DTMF dialstring playback durations in milliseconds */
#define RAKIA_DTMF_TONE_DURATION 250
#define RAKIA_DTMF_GAP_DURATION 100
#define RAKIA_DTMF_PAUSE_DURATION 3000

static void event_target_init (gpointer, gpointer);
static void channel_iface_init (gpointer, gpointer);
static void media_signalling_iface_init (gpointer, gpointer);
static void streamed_media_iface_init (gpointer, gpointer);
static void dtmf_iface_init (gpointer, gpointer);
static void call_state_iface_init (gpointer, gpointer);
static void hold_iface_init (gpointer, gpointer);

static void priv_session_dtmf_ready_cb (RakiaMediaSession *session,
                                        RakiaMediaChannel *channel);

G_DEFINE_TYPE_WITH_CODE (RakiaMediaChannel, rakia_media_channel,
    G_TYPE_OBJECT,
    G_IMPLEMENT_INTERFACE (RAKIA_TYPE_EVENT_TARGET, event_target_init);
    G_IMPLEMENT_INTERFACE (TP_TYPE_SVC_DBUS_PROPERTIES,
      tp_dbus_properties_mixin_iface_init);
    G_IMPLEMENT_INTERFACE (TP_TYPE_SVC_PROPERTIES_INTERFACE,
      tp_properties_mixin_iface_init);
    G_IMPLEMENT_INTERFACE (TP_TYPE_SVC_CHANNEL, channel_iface_init);
    G_IMPLEMENT_INTERFACE (TP_TYPE_SVC_CHANNEL_INTERFACE_GROUP,
      tp_group_mixin_iface_init);
    G_IMPLEMENT_INTERFACE (TP_TYPE_SVC_CHANNEL_INTERFACE_MEDIA_SIGNALLING,
      media_signalling_iface_init);
    G_IMPLEMENT_INTERFACE (TP_TYPE_SVC_CHANNEL_INTERFACE_DTMF,
      dtmf_iface_init);
    G_IMPLEMENT_INTERFACE (TP_TYPE_SVC_CHANNEL_INTERFACE_CALL_STATE,
      call_state_iface_init);
    G_IMPLEMENT_INTERFACE (TP_TYPE_SVC_CHANNEL_INTERFACE_HOLD,
      hold_iface_init);
    G_IMPLEMENT_INTERFACE (TP_TYPE_SVC_CHANNEL_TYPE_STREAMED_MEDIA,
      streamed_media_iface_init);
    G_IMPLEMENT_INTERFACE (TP_TYPE_EXPORTABLE_CHANNEL, NULL);
    G_IMPLEMENT_INTERFACE (TP_TYPE_CHANNEL_IFACE, NULL));

static const gchar *rakia_media_channel_interfaces[] = {
    TP_IFACE_CHANNEL_INTERFACE_GROUP,
    TP_IFACE_CHANNEL_INTERFACE_MEDIA_SIGNALLING,
    TP_IFACE_CHANNEL_INTERFACE_DTMF,
    TP_IFACE_CHANNEL_INTERFACE_CALL_STATE,
    TP_IFACE_CHANNEL_INTERFACE_HOLD,
    TP_IFACE_PROPERTIES_INTERFACE,
    NULL
};

/* properties */
enum
{
  PROP_CONNECTION = 1,
  PROP_OBJECT_PATH,
  PROP_CHANNEL_TYPE,
  PROP_HANDLE_TYPE,
  PROP_HANDLE,
  PROP_TARGET_ID,
  PROP_INITIATOR,
  PROP_INITIATOR_ID,
  PROP_REQUESTED,
  PROP_INTERFACES,
  PROP_CHANNEL_DESTROYED,
  PROP_CHANNEL_PROPERTIES,
  PROP_INITIAL_AUDIO,
  PROP_INITIAL_VIDEO,
  PROP_IMMUTABLE_STREAMS,
  PROP_CURRENTLY_SENDING_TONES,
  PROP_INITIAL_TONES,
  PROP_DEFERRED_TONES,
  /* Telepathy properties (see below too) */
  PROP_NAT_TRAVERSAL,
  PROP_STUN_SERVER,
  PROP_STUN_PORT,
  LAST_PROPERTY
};

/* TP channel properties */
enum
{
  TP_PROP_NAT_TRAVERSAL = 0,
  TP_PROP_STUN_SERVER,
  TP_PROP_STUN_PORT,
  NUM_TP_PROPS
};

static const TpPropertySignature media_channel_property_signatures[NUM_TP_PROPS] =
{
    { "nat-traversal",          G_TYPE_STRING },
    { "stun-server",            G_TYPE_STRING },
    { "stun-port",              G_TYPE_UINT },
};

/* signals */
enum
{
  SIG_INCOMING_CALL,
  NUM_SIGNALS
};

static guint signals[NUM_SIGNALS] = { 0 };


/* private structure */
struct _RakiaMediaChannelPrivate
{
  RakiaBaseConnection *conn;
  RakiaMediaSession *session;
  gchar *object_path;
  TpHandle handle;
  TpHandle initiator;
  GHashTable *call_states;
  gchar *stun_server;
  guint stun_port;
  TpDTMFPlayer *dtmf_player;
  gchar *initial_tones;
  gchar *deferred_tones;

  gboolean initial_audio;
  gboolean initial_video;
  gboolean immutable_streams;
  gboolean closed;
  gboolean dispose_has_run;
};

#define RAKIA_MEDIA_CHANNEL_GET_PRIVATE(chan) ((chan)->priv)

/***********************************************************************
 * Set: Gobject interface
 ***********************************************************************/

static void
rakia_media_channel_init (RakiaMediaChannel *self)
{
  RakiaMediaChannelPrivate *priv =
      G_TYPE_INSTANCE_GET_PRIVATE (self,
          RAKIA_TYPE_MEDIA_CHANNEL, RakiaMediaChannelPrivate);

  self->priv = priv;

  /* allocate any data required by the object here */
  priv->call_states = g_hash_table_new (NULL, NULL);

  /* initialise the properties mixin *before* GObject
   * sets the construct-time properties */
  tp_properties_mixin_init (G_OBJECT (self),
      G_STRUCT_OFFSET (RakiaMediaChannel, properties));
}

static void
rakia_media_channel_constructed (GObject *obj)
{
  RakiaMediaChannel *chan = RAKIA_MEDIA_CHANNEL (obj);
  RakiaMediaChannelPrivate *priv = RAKIA_MEDIA_CHANNEL_GET_PRIVATE (chan);
  TpBaseConnection *conn = (TpBaseConnection *)(priv->conn);
  GObjectClass *parent_object_class =
      G_OBJECT_CLASS (rakia_media_channel_parent_class);
  TpDBusDaemon *bus;
  TpHandleRepoIface *contact_repo;
  TpIntSet *add;

  if (parent_object_class->constructed != NULL)
    parent_object_class->constructed (obj);

  contact_repo = tp_base_connection_get_handles (conn,
      TP_HANDLE_TYPE_CONTACT);

  if (priv->handle != 0)
    tp_handle_ref (contact_repo, priv->handle);

  /* register object on the bus */
  bus = tp_base_connection_get_dbus_daemon (conn);

  DEBUG("registering object to dbus path=%s", priv->object_path);
  tp_dbus_daemon_register_object (bus, priv->object_path, obj);

  /* initialize group mixin */
  tp_group_mixin_init (obj,
                       G_STRUCT_OFFSET (RakiaMediaChannel, group),
                       contact_repo,
                       conn->self_handle);

  /* automatically add initiator to channel, but also ref them again (because
   * priv->initiator is the InitiatorHandle) */
  g_assert (priv->initiator != 0);
  tp_handle_ref (contact_repo, priv->initiator);

  add = tp_intset_new_containing (priv->initiator);
  tp_group_mixin_change_members (obj, "", add, NULL, NULL, NULL, 0, 0);
  tp_intset_destroy (add);

  /* We start off with lots of flags, and then delete them as we work out what
   * kind of channel we are, rather than trying to track what we need to
   * add/remove over time. We should always have the right flags before we are
   * advertised on the bus. */
  tp_group_mixin_change_flags (obj,
      TP_CHANNEL_GROUP_FLAG_CAN_ADD | TP_CHANNEL_GROUP_FLAG_CAN_REMOVE |
      TP_CHANNEL_GROUP_FLAG_CAN_RESCIND | TP_CHANNEL_GROUP_FLAG_PROPERTIES, 0);
}

static void rakia_media_channel_dispose (GObject *object);
static void rakia_media_channel_finalize (GObject *object);
static void rakia_media_channel_get_property (GObject    *object,
					    guint       property_id,
					    GValue     *value,
					    GParamSpec *pspec);
static void rakia_media_channel_set_property (GObject     *object,
					    guint        property_id,
					    const GValue *value,
					    GParamSpec   *pspec);

static void priv_create_session (RakiaMediaChannel *channel,
                                 nua_handle_t *nh,
                                 TpHandle peer);
static void priv_destroy_session(RakiaMediaChannel *channel);

static void priv_outbound_call (RakiaMediaChannel *channel,
                                TpHandle peer);

static gboolean rakia_media_channel_remove_with_reason (
                                                 GObject *iface,
                                                 TpHandle handle,
                                                 const gchar *message,
                                                 guint reason,
                                                 GError **error);

static void
rakia_media_channel_class_init (RakiaMediaChannelClass *klass)
{
  static TpDBusPropertiesMixinPropImpl channel_props[] = {
      { "ChannelType", "channel-type", NULL },
      { "Interfaces", "interfaces", NULL },
      { "TargetHandleType", "handle-type", NULL },
      { "TargetHandle", "handle", NULL },
      { "TargetID", "target-id", NULL },
      { "InitiatorHandle", "initiator", NULL },
      { "InitiatorID", "initiator-id", NULL },
      { "Requested", "requested", NULL },
      { NULL }
  };
  static TpDBusPropertiesMixinPropImpl streamed_media_props[] = {
      { "InitialAudio", "initial-audio", NULL },
      { "InitialVideo", "initial-video", NULL },
      { "ImmutableStreams", "immutable-streams", NULL },
      { NULL }
  };
  static TpDBusPropertiesMixinPropImpl dtmf_props[] = {
      { "CurrentlySendingTones", "currently-sending-tones", NULL },
      { "InitialTones", "initial-tones", NULL },
      { "DeferredTones", "deferred-tones", NULL },
      { NULL }
  };

  static TpDBusPropertiesMixinIfaceImpl prop_interfaces[] = {
      { TP_IFACE_CHANNEL,
        tp_dbus_properties_mixin_getter_gobject_properties,
        NULL,
        channel_props,
      },
      { TP_IFACE_CHANNEL_TYPE_STREAMED_MEDIA,
        tp_dbus_properties_mixin_getter_gobject_properties,
        NULL,
        streamed_media_props,
      },
      { TP_IFACE_CHANNEL_INTERFACE_DTMF,
        tp_dbus_properties_mixin_getter_gobject_properties,
        NULL,
        dtmf_props,
      },
      { NULL }
  };

  GObjectClass *object_class = G_OBJECT_CLASS (klass);
  GParamSpec *param_spec;

  DEBUG("enter");

  g_type_class_add_private (klass, sizeof (RakiaMediaChannelPrivate));

  object_class->constructed = rakia_media_channel_constructed;
  object_class->dispose = rakia_media_channel_dispose;
  object_class->finalize = rakia_media_channel_finalize;

  object_class->get_property = rakia_media_channel_get_property;
  object_class->set_property = rakia_media_channel_set_property;

  g_object_class_override_property (object_class, PROP_HANDLE_TYPE,
      "handle-type");
  g_object_class_override_property (object_class, PROP_HANDLE, "handle");
  g_object_class_override_property (object_class, PROP_OBJECT_PATH,
      "object-path");
  g_object_class_override_property (object_class, PROP_CHANNEL_TYPE,
      "channel-type");

  g_object_class_override_property (object_class, PROP_CHANNEL_DESTROYED,
      "channel-destroyed");
  g_object_class_override_property (object_class, PROP_CHANNEL_PROPERTIES,
      "channel-properties");

  param_spec = g_param_spec_object ("connection", "RakiaConnection object",
      "SIP connection object that owns this SIP media channel object.",
      RAKIA_TYPE_BASE_CONNECTION,
      G_PARAM_CONSTRUCT_ONLY | G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS);
  g_object_class_install_property (object_class, PROP_CONNECTION, param_spec);

  param_spec = g_param_spec_string ("nat-traversal", "NAT traversal mechanism",
      "A string representing the type of NAT traversal that should be "
      "performed for streams on this channel.",
      "none",
      G_PARAM_CONSTRUCT_ONLY | G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS);
  g_object_class_install_property (object_class, PROP_NAT_TRAVERSAL, param_spec);

  param_spec = g_param_spec_string ("stun-server", "STUN server",
      "IP or address of STUN server.", NULL,
      G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS);
  g_object_class_install_property (object_class, PROP_STUN_SERVER, param_spec);

  param_spec = g_param_spec_uint ("stun-port", "STUN port",
      "UDP port of STUN server.", 0, G_MAXUINT16, 0,
      G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS);
  g_object_class_install_property (object_class, PROP_STUN_PORT, param_spec);

  param_spec = g_param_spec_boxed ("interfaces", "Extra D-Bus interfaces",
      "Addition Channel.Interface.* interfaces", G_TYPE_STRV,
      G_PARAM_READABLE | G_PARAM_STATIC_STRINGS);
  g_object_class_install_property (object_class, PROP_INTERFACES, param_spec);

  param_spec = g_param_spec_string ("target-id", "Target SIP URI",
      "Currently empty, because this channel always has handle 0.",
      NULL,
      G_PARAM_READABLE | G_PARAM_STATIC_STRINGS);
  g_object_class_install_property (object_class, PROP_TARGET_ID, param_spec);

  param_spec = g_param_spec_uint ("initiator", "Channel initiator",
      "The TpHandle representing the contact who created the channel.",
      0, G_MAXUINT32, 0,
      G_PARAM_CONSTRUCT_ONLY | G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS);
  g_object_class_install_property (object_class, PROP_INITIATOR, param_spec);

  param_spec = g_param_spec_string ("initiator-id", "Creator URI",
      "The URI obtained by inspecting the initiator handle.",
      NULL,
      G_PARAM_READABLE | G_PARAM_STATIC_STRINGS);
  g_object_class_install_property (object_class, PROP_INITIATOR_ID, param_spec);

  param_spec = g_param_spec_boolean ("requested", "Requested?",
      "True if this channel was requested by the local user",
      FALSE,
      G_PARAM_READABLE | G_PARAM_STATIC_STRINGS);
  g_object_class_install_property (object_class, PROP_REQUESTED, param_spec);

  param_spec = g_param_spec_boolean ("initial-audio", "InitialAudio",
      "Whether the channel initially contained an audio stream",
      FALSE,
      G_PARAM_CONSTRUCT_ONLY | G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS);
  g_object_class_install_property (object_class, PROP_INITIAL_AUDIO,
      param_spec);

  param_spec = g_param_spec_boolean ("initial-video", "InitialVideo",
      "Whether the channel initially contained a video stream",
      FALSE,
      G_PARAM_CONSTRUCT_ONLY | G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS);
  g_object_class_install_property (object_class, PROP_INITIAL_VIDEO,
      param_spec);

  param_spec = g_param_spec_boolean ("immutable-streams", "ImmutableStreams",
      "Whether the set of streams on this channel are fixed once requested",
      FALSE,
      G_PARAM_CONSTRUCT_ONLY | G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS);
  g_object_class_install_property (object_class, PROP_IMMUTABLE_STREAMS,
      param_spec);

  param_spec = g_param_spec_boolean ("currently-sending-tones",
      "Currently sending tones",
      "True if the channel is currently sending DTMF tones",
      FALSE,
      G_PARAM_READABLE | G_PARAM_STATIC_STRINGS);
  g_object_class_install_property (object_class, PROP_CURRENTLY_SENDING_TONES,
      param_spec);

  param_spec = g_param_spec_string ("initial-tones", "Initial tones",
      "The initial DTMF tones to send after audio stream(s) are established.",
      NULL,
      G_PARAM_CONSTRUCT_ONLY | G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS);
  g_object_class_install_property (object_class, PROP_INITIAL_TONES,
      param_spec);

  param_spec = g_param_spec_string ("deferred-tones", "Deferred tones",
      "The DTMF tones deferred waiting for user input.",
      NULL,
      G_PARAM_READABLE | G_PARAM_STATIC_STRINGS);
  g_object_class_install_property (object_class, PROP_DEFERRED_TONES,
      param_spec);

  signals[SIG_INCOMING_CALL] =
      g_signal_new ("incoming-call",
                    G_OBJECT_CLASS_TYPE (klass),
                    G_SIGNAL_RUN_LAST,
                    0,
                    NULL, NULL,
                    g_cclosure_marshal_VOID__VOID,
                    G_TYPE_NONE, 0);

  tp_properties_mixin_class_init (object_class,
      G_STRUCT_OFFSET (RakiaMediaChannelClass, properties_class),
      media_channel_property_signatures, NUM_TP_PROPS, NULL);

  klass->dbus_props_class.interfaces =
      prop_interfaces;
  tp_dbus_properties_mixin_class_init (object_class,
      G_STRUCT_OFFSET (RakiaMediaChannelClass, dbus_props_class));

  tp_group_mixin_class_init (object_class,
                             G_STRUCT_OFFSET (RakiaMediaChannelClass, group_class),
                             _rakia_media_channel_add_member,
                             NULL);
  tp_group_mixin_class_allow_self_removal (object_class);
  tp_group_mixin_class_set_remove_with_reason_func(object_class,
                             rakia_media_channel_remove_with_reason);
  tp_group_mixin_init_dbus_properties (object_class);

}

static void
rakia_media_channel_get_property (GObject    *object,
                                  guint       property_id,
                                  GValue     *value,
                                  GParamSpec *pspec)
{
  RakiaMediaChannel *chan = RAKIA_MEDIA_CHANNEL (object);
  RakiaMediaChannelPrivate *priv = RAKIA_MEDIA_CHANNEL_GET_PRIVATE (chan);
  TpBaseConnection *base_conn = TP_BASE_CONNECTION (priv->conn);

  switch (property_id) {
    case PROP_CONNECTION:
      g_value_set_object (value, priv->conn);
      break;
    case PROP_OBJECT_PATH:
      g_value_set_string (value, priv->object_path);
      break;
    case PROP_CHANNEL_TYPE:
      g_value_set_static_string (value, TP_IFACE_CHANNEL_TYPE_STREAMED_MEDIA);
      break;
    case PROP_HANDLE:
      g_value_set_uint (value, priv->handle);
      break;
    case PROP_HANDLE_TYPE:
      g_value_set_uint (value, priv->handle?
          TP_HANDLE_TYPE_CONTACT : TP_HANDLE_TYPE_NONE);
      break;
    case PROP_TARGET_ID:
      if (priv->handle != 0)
        {
          TpHandleRepoIface *repo = tp_base_connection_get_handles (
              base_conn, TP_HANDLE_TYPE_CONTACT);

          g_value_set_string (value, tp_handle_inspect (repo, priv->handle));
        }
      else
        g_value_set_static_string (value, "");
      break;
    case PROP_INITIATOR:
      g_value_set_uint (value, priv->initiator);
      break;
    case PROP_INITIATOR_ID:
        {
          TpHandleRepoIface *repo = tp_base_connection_get_handles (
              base_conn, TP_HANDLE_TYPE_CONTACT);

          g_value_set_string (value, tp_handle_inspect (repo, priv->initiator));
        }
      break;
    case PROP_REQUESTED:
      g_value_set_boolean (value, (priv->initiator == base_conn->self_handle));
      break;
    case PROP_INTERFACES:
      g_value_set_static_boxed (value, rakia_media_channel_interfaces);
      break;
    case PROP_CHANNEL_DESTROYED:
      g_value_set_boolean (value, priv->closed);
      break;
    case PROP_CHANNEL_PROPERTIES:
      g_value_take_boxed (value,
          tp_dbus_properties_mixin_make_properties_hash (object,
              TP_IFACE_CHANNEL, "ChannelType",
              TP_IFACE_CHANNEL, "TargetHandleType",
              TP_IFACE_CHANNEL, "TargetHandle",
              TP_IFACE_CHANNEL, "TargetID",
              TP_IFACE_CHANNEL, "InitiatorHandle",
              TP_IFACE_CHANNEL, "InitiatorID",
              TP_IFACE_CHANNEL, "Requested",
              TP_IFACE_CHANNEL, "Interfaces",
              TP_IFACE_CHANNEL_TYPE_STREAMED_MEDIA, "InitialAudio",
              TP_IFACE_CHANNEL_TYPE_STREAMED_MEDIA, "InitialVideo",
              TP_IFACE_CHANNEL_TYPE_STREAMED_MEDIA, "ImmutableStreams",
              NULL));
      break;
    case PROP_INITIAL_AUDIO:
      g_value_set_boolean (value, priv->initial_audio);
      break;
    case PROP_INITIAL_VIDEO:
      g_value_set_boolean (value, priv->initial_video);
      break;
    case PROP_IMMUTABLE_STREAMS:
      g_value_set_boolean (value, priv->immutable_streams);
      break;
    case PROP_STUN_SERVER:
      g_value_set_string (value, priv->stun_server);
      break;
    case PROP_STUN_PORT:
      g_value_set_uint (value, priv->stun_port);
      break;
    case PROP_CURRENTLY_SENDING_TONES:
      g_value_set_boolean (value,
          priv->dtmf_player != NULL
            && tp_dtmf_player_is_active (priv->dtmf_player));
      break;
    case PROP_INITIAL_TONES:
      if (priv->initial_tones == NULL)
        g_value_set_static_string (value, "");
      else
        g_value_set_string (value, priv->initial_tones);
      break;
    case PROP_DEFERRED_TONES:
      if (priv->deferred_tones == NULL)
        g_value_set_static_string (value, "");
      else
        g_value_set_string (value, priv->deferred_tones);
      break;
    default:
      /* Some properties live in the mixin */
      {
        const gchar *param_name;
        guint tp_property_id;
        GValue *tp_property_value;

        param_name = g_param_spec_get_name (pspec);
        if (G_LIKELY (tp_properties_mixin_has_property (object, param_name,
                        &tp_property_id)))
          {
            tp_property_value =
              chan->properties.properties[tp_property_id].value;

            if (G_LIKELY (tp_property_value != NULL))
              {
                g_value_copy (tp_property_value, value);
                return;
              }
          }
      }

      G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec);
      break;
  }
}

static gboolean
rakia_media_channel_set_tp_property (RakiaMediaChannel *chan,
                                     const GValue *value,
                                     GParamSpec   *pspec)
{
  GObject *obj = (GObject *) chan;
  const gchar *param_name = g_param_spec_get_name (pspec);
  guint tp_property_id;

  if (G_LIKELY (tp_properties_mixin_has_property (obj, param_name,
                  &tp_property_id)))
    {
      tp_properties_mixin_change_value (obj, tp_property_id,
          value, NULL);
      tp_properties_mixin_change_flags (obj, tp_property_id,
          TP_PROPERTY_FLAG_READ, 0, NULL);
      return TRUE;
    }
  else
    {
      WARNING("Telepathy property '%s' is not defined for media channels",
              param_name);
      return FALSE;
    }
}

static void
rakia_media_channel_set_property (GObject     *object,
				guint        property_id,
				const GValue *value,
				GParamSpec   *pspec)
{
  RakiaMediaChannel *chan = RAKIA_MEDIA_CHANNEL (object);
  RakiaMediaChannelPrivate *priv = RAKIA_MEDIA_CHANNEL_GET_PRIVATE (chan);

  switch (property_id) {
    case PROP_HANDLE_TYPE:
    case PROP_CHANNEL_TYPE:
      /* this property is writable in the interface, but not actually
       * meaningfully changable on this channel, so we do nothing */
      break;
    case PROP_CONNECTION:
      priv->conn = g_value_dup_object (value);
      break;
    case PROP_OBJECT_PATH:
      g_free (priv->object_path);
      priv->object_path = g_value_dup_string (value);
      break;
    case PROP_HANDLE:
      /* XXX: this property is defined as writable,
       * but don't set it after construction, mmkay? */
      /* we don't ref it here because we don't necessarily have access to the
       * contact repo yet - instead we ref it in constructed. */
      priv->handle = g_value_get_uint (value);
      break;
    case PROP_INITIATOR:
      /* similarly we can't ref this yet */
      priv->initiator = g_value_get_uint (value);
      break;
    case PROP_INITIAL_AUDIO:
      priv->initial_audio = g_value_get_boolean (value);
      break;
    case PROP_INITIAL_VIDEO:
      priv->initial_video = g_value_get_boolean (value);
      break;
    case PROP_IMMUTABLE_STREAMS:
      priv->immutable_streams = g_value_get_boolean (value);
      break;
    case PROP_STUN_SERVER:
      priv->stun_server = g_value_dup_string (value);
      /* Also expose as a legacy Telepathy property */
      rakia_media_channel_set_tp_property (chan, value, pspec);
      break;
    case PROP_STUN_PORT:
      priv->stun_port = g_value_get_uint (value);
      /* Also expose as a legacy Telepathy property */
      rakia_media_channel_set_tp_property (chan, value, pspec);
      break;
    case PROP_INITIAL_TONES:
      priv->initial_tones = g_value_dup_string (value);
      break;
    default:
      /* some properties live in the mixin */
      if (rakia_media_channel_set_tp_property (chan, value, pspec))
        return;

      G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec);
      break;
  }
}

static void
rakia_media_channel_dispose (GObject *object)
{
  RakiaMediaChannel *self = RAKIA_MEDIA_CHANNEL (object);
  RakiaMediaChannelPrivate *priv = RAKIA_MEDIA_CHANNEL_GET_PRIVATE (self);
  TpHandleRepoIface *contact_handles;

  if (priv->dispose_has_run)
    return;

  DEBUG("enter");

  priv->dispose_has_run = TRUE;

  if (!priv->closed)
    rakia_media_channel_close (self);

  if (priv->dtmf_player != NULL)
    g_object_unref (priv->dtmf_player);

  contact_handles = tp_base_connection_get_handles (
      TP_BASE_CONNECTION (priv->conn), TP_HANDLE_TYPE_CONTACT);

  tp_handle_unref (contact_handles, priv->initiator);
  priv->initiator = 0;

  g_object_unref (priv->conn);

  if (G_OBJECT_CLASS (rakia_media_channel_parent_class)->dispose)
    G_OBJECT_CLASS (rakia_media_channel_parent_class)->dispose (object);

  DEBUG("exit");
}

static void
rakia_media_channel_finalize (GObject *object)
{
  RakiaMediaChannel *self = RAKIA_MEDIA_CHANNEL (object);
  RakiaMediaChannelPrivate *priv = RAKIA_MEDIA_CHANNEL_GET_PRIVATE (self);

  g_hash_table_unref (priv->call_states);

  g_free (priv->initial_tones);
  g_free (priv->deferred_tones);

  g_free (priv->stun_server);

  g_free (priv->object_path);

  tp_group_mixin_finalize (object);

  tp_properties_mixin_finalize (object);

  G_OBJECT_CLASS (rakia_media_channel_parent_class)->finalize (object);

  DEBUG("exit");
}

/***********************************************************************
 * Set: Channel interface implementation (same for 0.12/0.13)
 ***********************************************************************/

/**
 * rakia_media_channel_close_async
 *
 * Implements DBus method Close
 * on interface org.freedesktop.Telepathy.Channel
 */
static void
rakia_media_channel_dbus_close (TpSvcChannel *iface,
                                DBusGMethodInvocation *context)
{
  RakiaMediaChannel *self = RAKIA_MEDIA_CHANNEL (iface);

  rakia_media_channel_close (self);
  tp_svc_channel_return_from_close (context);
}

void
rakia_media_channel_close (RakiaMediaChannel *obj)
{
  RakiaMediaChannelPrivate *priv;

  DEBUG("enter");

  g_assert (RAKIA_IS_MEDIA_CHANNEL (obj));
  priv = RAKIA_MEDIA_CHANNEL_GET_PRIVATE (obj);

  if (priv->closed)
    return;

  priv->closed = TRUE;

  if (priv->session) {
    rakia_media_session_terminate (priv->session);
    g_assert (priv->session == NULL);
  }

  tp_svc_channel_emit_closed ((TpSvcChannel *)obj);

  return;
}

/**
 * rakia_media_channel_get_channel_type
 *
 * Implements DBus method GetChannelType
 * on interface org.freedesktop.Telepathy.Channel
 */
static void
rakia_media_channel_get_channel_type (TpSvcChannel *obj,
                                    DBusGMethodInvocation *context)
{
  tp_svc_channel_return_from_get_channel_type (context,
      TP_IFACE_CHANNEL_TYPE_STREAMED_MEDIA);
}


/**
 * rakia_media_channel_get_handle
 *
 * Implements DBus method GetHandle
 * on interface org.freedesktop.Telepathy.Channel
 */
static void
rakia_media_channel_get_handle (TpSvcChannel *iface,
                              DBusGMethodInvocation *context)
{
  RakiaMediaChannel *self = RAKIA_MEDIA_CHANNEL (iface);
  RakiaMediaChannelPrivate *priv = RAKIA_MEDIA_CHANNEL_GET_PRIVATE (self);

  if (priv->handle != 0)
    tp_svc_channel_return_from_get_handle (context, TP_HANDLE_TYPE_CONTACT,
          priv->handle);
  else
    tp_svc_channel_return_from_get_handle (context, TP_HANDLE_TYPE_NONE, 0);
}

/**
 * rakia_media_channel_get_interfaces
 *
 * Implements DBus method GetInterfaces
 * on interface org.freedesktop.Telepathy.Channel
 */
static void
rakia_media_channel_get_interfaces (TpSvcChannel *iface,
                                  DBusGMethodInvocation *context)
{
  tp_svc_channel_return_from_get_interfaces (context,
      rakia_media_channel_interfaces);
}

/***********************************************************************
 * Set: Channel.Interface.MediaSignalling Telepathy-0.13 interface
 ***********************************************************************/

/**
 * rakia_media_channel_get_session_handlers
 *
 * Implements DBus method GetSessionHandlers
 * on interface org.freedesktop.Telepathy.Channel.Interface.MediaSignalling
 *
 * @error: Used to return a pointer to a GError detailing any error
 *         that occured, DBus will throw the error only if this
 *         function returns false.
 *
 * Returns: TRUE if successful, FALSE if an error was thrown.
 */
static void
rakia_media_channel_get_session_handlers (TpSvcChannelInterfaceMediaSignalling *iface,
                                        DBusGMethodInvocation *context)
{
  RakiaMediaChannel *self = RAKIA_MEDIA_CHANNEL (iface);
  RakiaMediaChannelPrivate *priv;
  GPtrArray *ret;
  GValue handler = { 0 };

  DEBUG("enter");

  g_assert (RAKIA_IS_MEDIA_CHANNEL (self));

  priv = RAKIA_MEDIA_CHANNEL_GET_PRIVATE (self);

  ret = g_ptr_array_new ();

  if (priv->session)
    {
      GType handler_type;
      gchar *path;

      g_object_get (priv->session,
                    "object-path", &path,
                    NULL);

      handler_type = dbus_g_type_get_struct ("GValueArray",
                                             DBUS_TYPE_G_OBJECT_PATH,
                                             G_TYPE_STRING,
                                             G_TYPE_INVALID);

      g_value_init (&handler, handler_type);
      g_value_take_boxed (&handler,
                          dbus_g_type_specialized_construct (handler_type));

      dbus_g_type_struct_set (&handler,
                              0, path,
                              1, "rtp",
                              G_MAXUINT);

      g_free (path);

      g_ptr_array_add (ret, g_value_get_boxed (&handler));
    }

  tp_svc_channel_interface_media_signalling_return_from_get_session_handlers (
      context, ret);

  if (G_IS_VALUE(&handler))
    g_value_unset (&handler);

  g_ptr_array_unref (ret);
}


/***********************************************************************
 * Set: Channel.Type.StreamedMedia Telepathy-0.13 interface
 ***********************************************************************/

/**
 * rakia_media_channel_list_streams
 *
 * Implements D-Bus method ListStreams
 * on interface org.freedesktop.Telepathy.Channel.Type.StreamedMedia
 */
static void
rakia_media_channel_list_streams (TpSvcChannelTypeStreamedMedia *iface,
                                DBusGMethodInvocation *context)
{
  RakiaMediaChannel *self = RAKIA_MEDIA_CHANNEL (iface);
  RakiaMediaChannelPrivate *priv;
  GPtrArray *ret = NULL;

  priv = RAKIA_MEDIA_CHANNEL_GET_PRIVATE (self);

  ret = g_ptr_array_new ();

  if (priv->session != NULL)
    rakia_media_session_list_streams (priv->session, ret);

  tp_svc_channel_type_streamed_media_return_from_list_streams (context, ret);

  g_boxed_free (TP_ARRAY_TYPE_MEDIA_STREAM_INFO_LIST, ret);
}

/**
 * rakia_media_channel_remove_streams
 *
 * Implements D-Bus method RemoveStreams
 * on interface org.freedesktop.Telepathy.Channel.Type.StreamedMedia
 */
static void
rakia_media_channel_remove_streams (TpSvcChannelTypeStreamedMedia *iface,
                                  const GArray *streams,
                                  DBusGMethodInvocation *context)
{
  RakiaMediaChannel *self = RAKIA_MEDIA_CHANNEL (iface);
  RakiaMediaChannelPrivate *priv;
  GError *error = NULL;

  priv = RAKIA_MEDIA_CHANNEL_GET_PRIVATE (self);

  if (priv->immutable_streams)
    {
      error = g_error_new (TP_ERRORS, TP_ERROR_NOT_IMPLEMENTED,
          "Cannot remove streams from the existing channel");
    }
  else if (priv->session != NULL)
    {
       rakia_media_session_remove_streams(priv->session,
                                        streams,
                                        &error);
    }
  else
    {
      error = g_error_new (TP_ERRORS, TP_ERROR_NOT_AVAILABLE,
                           "No session is available");
    }

  if (error != NULL)
    {
      dbus_g_method_return_error (context, error);
      g_error_free (error);
      return;
    }

  tp_svc_channel_type_streamed_media_return_from_remove_streams (context);
}

/**
 * rakia_media_channel_request_stream_direction
 *
 * Implements D-Bus method RequestStreamDirection
 * on interface org.freedesktop.Telepathy.Channel.Type.StreamedMedia
 */
static void
rakia_media_channel_request_stream_direction (TpSvcChannelTypeStreamedMedia *iface,
                                            guint stream_id,
                                            guint stream_direction,
                                            DBusGMethodInvocation *context)
{
  RakiaMediaChannel *self = RAKIA_MEDIA_CHANNEL (iface);
  RakiaMediaChannelPrivate *priv;
  GError *error = NULL;

  priv = RAKIA_MEDIA_CHANNEL_GET_PRIVATE (self);

  if (priv->immutable_streams)
    {
      GError e = { TP_ERRORS, TP_ERROR_NOT_AVAILABLE,
          "Cannot change directions on an immutable channel" };
      dbus_g_method_return_error (context, &e);
      return;
    }

  if (priv->session != NULL)
    {
      rakia_media_session_request_stream_direction (priv->session,
                                                  stream_id,
                                                  stream_direction,
                                                  &error);
    }
  else
    {
      error = g_error_new (TP_ERRORS, TP_ERROR_NOT_AVAILABLE,
                           "The media session is not available");
    }

  if (error == NULL)
    {
      tp_svc_channel_type_streamed_media_return_from_request_stream_direction (context);
    }
  else
    {
      dbus_g_method_return_error (context, error);
      g_error_free (error);
    }
}


/**
 * rakia_media_channel_request_streams
 *
 * Implements D-Bus method RequestStreams
 * on interface org.freedesktop.Telepathy.Channel.Type.StreamedMedia
 */
static void
rakia_media_channel_request_streams (TpSvcChannelTypeStreamedMedia *iface,
                                   guint contact_handle,
                                   const GArray *types,
                                   DBusGMethodInvocation *context)
{
  RakiaMediaChannel *self = RAKIA_MEDIA_CHANNEL (iface);
  GError *error = NULL;
  GPtrArray *ret = NULL;
  RakiaMediaChannelPrivate *priv;
  TpHandleRepoIface *contact_repo;

  DEBUG("enter");

  priv = RAKIA_MEDIA_CHANNEL_GET_PRIVATE (self);

  if (priv->immutable_streams)
    {
      GError e = { TP_ERRORS, TP_ERROR_NOT_AVAILABLE,
          "Cannot add streams to the immutable channel" };
      dbus_g_method_return_error (context, &e);
      return;
    }

  contact_repo = tp_base_connection_get_handles (
      (TpBaseConnection *)(priv->conn), TP_HANDLE_TYPE_CONTACT);

  if (!tp_handle_is_valid (contact_repo, contact_handle, &error))
    {
      dbus_g_method_return_error (context, error);
      g_error_free (error);
      return;
    }

  priv_outbound_call (self, contact_handle);

  ret = g_ptr_array_sized_new (types->len);

  if (rakia_media_session_request_streams (priv->session, types, ret, &error))
    {
      g_assert (types->len == ret->len);
      tp_svc_channel_type_streamed_media_return_from_request_streams (context,
                                                                      ret);
    }
  else
    {
      dbus_g_method_return_error (context, error);
      g_error_free (error);
    }

  g_boxed_free (TP_ARRAY_TYPE_MEDIA_STREAM_INFO_LIST, ret);

  DEBUG ("exit");
}

/***********************************************************************
 * Set: sip-media-channel API towards sip-connection
 ***********************************************************************/

void
rakia_media_channel_create_initial_streams (RakiaMediaChannel *self)
{
  RakiaMediaChannelPrivate *priv = RAKIA_MEDIA_CHANNEL_GET_PRIVATE (self);

  g_assert (priv->initiator != priv->handle);

  /* RequestChannel(None, 0) => channel is anonymous:
   * caller uses RequestStreams to set the peer and start the call. */
  if (priv->handle == 0)
    return;

  priv_outbound_call (self, priv->handle);

  g_assert (priv->session != NULL);

  if (priv->initial_audio)
    rakia_media_session_add_stream (priv->session,
        TP_MEDIA_STREAM_TYPE_AUDIO,
        TP_MEDIA_STREAM_DIRECTION_BIDIRECTIONAL,
        TRUE);

  if (priv->initial_video)
    rakia_media_session_add_stream (priv->session,
        TP_MEDIA_STREAM_TYPE_VIDEO,
        TP_MEDIA_STREAM_DIRECTION_BIDIRECTIONAL,
        TRUE);
}

/*
 * Handles an incoming call, called shortly after the channel
 * has been created with initiator handle of the sender, when remote SDP
 * session data are reported by the NUA stack.
 */
static void
rakia_media_channel_handle_incoming_call (RakiaMediaChannel *self,
                                          nua_handle_t *nh,
                                          const sdp_session_t *sdp)
{
  RakiaMediaChannelPrivate *priv = RAKIA_MEDIA_CHANNEL_GET_PRIVATE (self);
  TpBaseConnection *conn = TP_BASE_CONNECTION (priv->conn);

  g_assert (priv->initiator != conn->self_handle);
  g_assert (priv->session == NULL);

  if (sdp != NULL)
    {
      /* Get the initial media properties from the session offer */
      const sdp_media_t *media;
  
      for (media = sdp->sdp_media; media != NULL; media = media->m_next)
        {
          if (media->m_rejected || media->m_port == 0)
            continue;
  
          switch (media->m_type)
            {
            case sdp_media_audio:
              priv->initial_audio = TRUE;
              DEBUG("has initial audio");
              break;
            case sdp_media_video:
              priv->initial_video = TRUE;
              DEBUG("has initial video");
              break;
            default:
              break;
            }
        }
    }

  /* Tell the factory to emit NewChannel(s) */
  g_signal_emit (self, signals[SIG_INCOMING_CALL], 0);

  /* Offer the session handler to the client */
  priv_create_session (self, nh, priv->initiator);

  g_assert (priv->session != NULL);
  rakia_media_session_receive_invite (priv->session);
}

static gboolean
priv_nua_i_invite_cb (RakiaMediaChannel *self,
                      const RakiaNuaEvent  *ev,
                      tagi_t             tags[],
                      gpointer           foo)
{
  RakiaMediaChannelPrivate *priv = RAKIA_MEDIA_CHANNEL_GET_PRIVATE (self);

  /* nua_i_invite delivered for a bound handle means a re-INVITE */

  g_return_val_if_fail (priv->session != NULL, FALSE);

  rakia_media_session_receive_reinvite (priv->session);

  return TRUE;
}

static guint
rakia_media_channel_get_call_state (RakiaMediaChannel *self,
                                    TpHandle peer)
{
  RakiaMediaChannelPrivate *priv = RAKIA_MEDIA_CHANNEL_GET_PRIVATE (self);

  return GPOINTER_TO_UINT (g_hash_table_lookup (priv->call_states,
      GUINT_TO_POINTER (peer)));
}

static void
rakia_media_channel_peer_error (RakiaMediaChannel *self,
                                TpHandle peer,
                                guint status,
                                const char* message)
{
  TpGroupMixin *mixin = TP_GROUP_MIXIN (self);
  TpIntSet *remove;
  guint reason = TP_CHANNEL_GROUP_CHANGE_REASON_ERROR;

  switch (status)
    {
    case 410:
    case 604:
      reason = TP_CHANNEL_GROUP_CHANGE_REASON_INVALID_CONTACT;
      break;
    case 486:
    case 600:
      reason = TP_CHANNEL_GROUP_CHANGE_REASON_BUSY;
      break;
    case 408:
      reason = TP_CHANNEL_GROUP_CHANGE_REASON_NO_ANSWER;
      break;
    case 404:
    case 480:
      reason = (rakia_media_channel_get_call_state (self, peer)
             & RAKIA_CHANNEL_CALL_STATE_PROCEEDING_MASK)
          ? TP_CHANNEL_GROUP_CHANGE_REASON_NO_ANSWER
          : TP_CHANNEL_GROUP_CHANGE_REASON_OFFLINE;
      break;
    case 603:
      /* No reason means roughly "rejected" */
      reason = TP_CHANNEL_GROUP_CHANGE_REASON_NONE;
      break;
    case 403:
    case 401:
    case 407:
      reason = TP_CHANNEL_GROUP_CHANGE_REASON_PERMISSION_DENIED;
      break;
    }

  if (message == NULL || !g_utf8_validate (message, -1, NULL))
    message = "";

  remove = tp_intset_new ();
  tp_intset_add (remove, peer);
  tp_intset_add (remove, mixin->self_handle);
  tp_group_mixin_change_members ((GObject *)self, message,
      NULL, remove, NULL, NULL, peer, reason);
  tp_intset_destroy (remove);
}

guint
rakia_media_channel_change_call_state (RakiaMediaChannel *self,
                                       TpHandle peer,
                                       guint flags_add,
                                       guint flags_remove)
{
  RakiaMediaChannelPrivate *priv = RAKIA_MEDIA_CHANNEL_GET_PRIVATE (self);
  gpointer key = GUINT_TO_POINTER (peer);
  guint old_state;
  guint new_state;

  /* XXX: check if the peer is a member? */

  old_state = GPOINTER_TO_UINT (g_hash_table_lookup (priv->call_states, key));
  new_state = (old_state | flags_add) & ~flags_remove;

  if (new_state != old_state)
    {
      DEBUG ("setting call state %u for peer %u", new_state, peer);
      if (new_state == 0)
        g_hash_table_remove (priv->call_states, key);
      else
        g_hash_table_replace (priv->call_states, key,
                              GUINT_TO_POINTER (new_state));

      tp_svc_channel_interface_call_state_emit_call_state_changed (self,
                                                                   peer,
                                                                   new_state);
    }

  return new_state;
}

static gboolean
priv_nua_i_bye_cb (RakiaMediaChannel *self,
                   const RakiaNuaEvent  *ev,
                   tagi_t             tags[],
                   gpointer           foo)
{
  RakiaMediaChannelPrivate *priv = RAKIA_MEDIA_CHANNEL_GET_PRIVATE (self);
  TpGroupMixin *mixin = TP_GROUP_MIXIN (self);
  TpIntSet *remove;
  TpHandle peer;

  g_return_val_if_fail (priv->session != NULL, FALSE);

  peer = rakia_media_session_get_peer (priv->session);
  remove = tp_intset_new ();
  tp_intset_add (remove, peer);
  tp_intset_add (remove, mixin->self_handle);

  tp_group_mixin_change_members ((GObject *) self, "",
     NULL, remove, NULL, NULL,
     peer, TP_CHANNEL_GROUP_CHANGE_REASON_NONE);

  tp_intset_destroy (remove);

  return TRUE;
}

static gboolean
priv_nua_i_cancel_cb (RakiaMediaChannel *self,
                      const RakiaNuaEvent  *ev,
                      tagi_t             tags[],
                      gpointer           foo)
{
  RakiaMediaChannelPrivate *priv = RAKIA_MEDIA_CHANNEL_GET_PRIVATE (self);
  TpGroupMixin *mixin = TP_GROUP_MIXIN (self);
  TpIntSet *remove;
  TpHandle actor = 0;
  TpHandle peer;
  const sip_reason_t *reason;
  guint cause = 0;
  const gchar *message = NULL;

  g_return_val_if_fail (priv->session != NULL, FALSE);

  /* FIXME: implement cancellation of an incoming re-INVITE, if ever
   * found in real usage and not caused by a request timeout */

  if (ev->sip != NULL)
    for (reason = ev->sip->sip_reason;
         reason != NULL;
         reason = reason->re_next)
      {
        const char *protocol = reason->re_protocol;
        if (protocol == NULL || strcmp (protocol, "SIP") != 0)
          continue;
        if (reason->re_cause != NULL)
          {
            cause = (guint) g_ascii_strtoull (reason->re_cause, NULL, 10);
            message = reason->re_text;
            break;
          }
      }

  peer = rakia_media_session_get_peer (priv->session);

  switch (cause)
    {
    case 200:
    case 603:
      /* The user must have acted on another branch of the forked call */
      actor = mixin->self_handle;
      break;
    default:
      actor = peer;
    }

  if (message == NULL || !g_utf8_validate (message, -1, NULL))
    message = "";

  remove = tp_intset_new ();
  tp_intset_add (remove, peer);
  tp_intset_add (remove, mixin->self_handle);

  tp_group_mixin_change_members ((GObject *) self, message,
      NULL, remove, NULL, NULL,
      actor, TP_CHANNEL_GROUP_CHANGE_REASON_NONE);

  tp_intset_destroy (remove);

  return TRUE;
}

static gboolean
priv_nua_i_state_cb (RakiaMediaChannel *self,
                     const RakiaNuaEvent  *ev,
                     tagi_t             tags[],
                     gpointer           foo)
{
  RakiaMediaChannelPrivate *priv = RAKIA_MEDIA_CHANNEL_GET_PRIVATE (self);
  const sdp_session_t *r_sdp = NULL;
  int offer_recv = 0;
  int answer_recv = 0;
  int ss_state = nua_callstate_init;
  gint status = ev->status;
  TpHandle peer;

  tl_gets(tags,
          NUTAG_CALLSTATE_REF(ss_state),
          NUTAG_OFFER_RECV_REF(offer_recv),
          NUTAG_ANSWER_RECV_REF(answer_recv),
          SOATAG_REMOTE_SDP_REF(r_sdp),
          TAG_END());

  DEBUG("call with handle %p is %s", ev->nua_handle, nua_callstate_name (ss_state));

  if (ss_state == nua_callstate_received && priv->session == NULL)
    {
      /* We get the session data for initial media properties with this event;
       * initialize the session before we can create any streams below.
       */
      rakia_media_channel_handle_incoming_call (self, ev->nua_handle, r_sdp);
    }

  g_return_val_if_fail (priv->session != NULL, FALSE);

  if (r_sdp)
    {
      g_return_val_if_fail (answer_recv || offer_recv, FALSE);
      if (!rakia_media_session_set_remote_media (priv->session, r_sdp))
        {
          rakia_media_channel_close (self);
          return TRUE;
        }
    }

  peer = rakia_media_session_get_peer (priv->session);

  switch ((enum nua_callstate)ss_state)
    {
    case nua_callstate_proceeding:
      switch (status)
        {
          case 180:
            rakia_media_channel_change_call_state (self, peer,
                    TP_CHANNEL_CALL_STATE_RINGING, 0);
            break;
          case 182:
            rakia_media_channel_change_call_state (self, peer,
                    TP_CHANNEL_CALL_STATE_QUEUED, 0);
            break;
          case 183:
            rakia_media_channel_change_call_state (self, peer,
                    TP_CHANNEL_CALL_STATE_IN_PROGRESS, 0);
            break;
        }
      break;

    case nua_callstate_completing:
      /* In auto-ack mode, we don't need to call nua_ack(), see NUTAG_AUTOACK() */
      break;

    case nua_callstate_ready:

      /* Clear any pre-establishment call states */
      rakia_media_channel_change_call_state (self, peer, 0,
          RAKIA_CHANNEL_CALL_STATE_PROCEEDING_MASK);

      if (status < 300)
        {
          TpIntSet *add = tp_intset_new_containing (peer);

          tp_group_mixin_change_members ((GObject *) self,
                                         "",
                                         add,  /* add */
                                         NULL, /* remove */
                                         NULL,
                                         NULL,
                                         peer,
                                         TP_CHANNEL_GROUP_CHANGE_REASON_NONE);

          tp_intset_destroy (add);

          rakia_media_session_accept (priv->session);
        }
      else if (status == 491)
        rakia_media_session_resolve_glare (priv->session);
      else
        {
          /* Was something wrong with our re-INVITE? We can't cope anyway. */
          MESSAGE ("can't handle non-fatal response %d %s", status, ev->text);
          rakia_media_session_terminate (priv->session);
        }
      break;

    case nua_callstate_terminated:
      /* In cases of self-inflicted termination,
       * we should have already gone through the moves */
      if (rakia_media_session_get_state (priv->session)
          == RAKIA_MEDIA_SESSION_STATE_ENDED)
        break;

      if (status >= 300)
        {
          rakia_media_channel_peer_error (
                self, peer, status, ev->text);
        }

      rakia_media_session_change_state (priv->session,
                                        RAKIA_MEDIA_SESSION_STATE_ENDED);
      break;

    default:
      break;
  }

  return TRUE;
}

static void priv_session_state_changed_cb (RakiaMediaSession *session,
					   guint old_state,
                                           guint state,
					   RakiaMediaChannel *channel)
{
  RakiaMediaChannelPrivate *priv = RAKIA_MEDIA_CHANNEL_GET_PRIVATE (channel);
  TpGroupMixin *mixin = TP_GROUP_MIXIN (channel);
  TpHandle self_handle;
  TpHandle peer;
  TpIntSet *set = NULL;

  DEBUG("enter");

  self_handle = mixin->self_handle;
  peer = rakia_media_session_get_peer (session);

  switch (state)
    {
    case RAKIA_MEDIA_SESSION_STATE_INVITE_SENT:
      g_assert (priv->initiator == self_handle);

      /* add the peer to remote pending */
      set = tp_intset_new_containing (peer);
      tp_group_mixin_change_members ((GObject *)channel,
                                     "",
                                     NULL,    /* add */
                                     NULL,    /* remove */
                                     NULL,    /* local pending */
                                     set,     /* remote pending */
                                     self_handle,        /* actor */
                                     TP_CHANNEL_GROUP_CHANGE_REASON_INVITED);

      /* update flags: no more adding */
      tp_group_mixin_change_flags ((GObject *)channel, 0,
          TP_CHANNEL_GROUP_FLAG_CAN_ADD);

      break;

    case RAKIA_MEDIA_SESSION_STATE_INVITE_RECEIVED:
      /* add ourself to local pending */
      set = tp_intset_new_containing (self_handle);
      tp_group_mixin_change_members ((GObject *) channel, "",
                                     NULL,          /* add */
                                     NULL,          /* remove */
                                     set,           /* local pending */
                                     NULL,          /* remote pending */
                                     priv->initiator, /* actor */
                                     TP_CHANNEL_GROUP_CHANGE_REASON_INVITED);

      /* No adding more members to the incoming call. Therefore also not
       * possible to add anyone to remote-pending, so rescinding would make
       * utterly no sense. We also disallow removing the remote peer if
       * we are not the initiator, so disallow that too.
       * Removing yourself to end the call is not represented by group flags.
       */
      tp_group_mixin_change_flags ((GObject *) channel, 0,
          TP_CHANNEL_GROUP_FLAG_CAN_ADD | TP_CHANNEL_GROUP_FLAG_CAN_REMOVE |
          TP_CHANNEL_GROUP_FLAG_CAN_RESCIND);

      break;

    case RAKIA_MEDIA_SESSION_STATE_ACTIVE:
      if (priv->initiator == self_handle)
        {
          if (!tp_handle_set_is_member (mixin->remote_pending, peer))
            break; /* no-op */

          /* the peer has promoted itself to members */
          set = tp_intset_new_containing (peer);
          tp_group_mixin_change_members ((GObject *)channel, "",
                                         set,     /* add */
                                         NULL,    /* remove */
                                         NULL,
                                         NULL,
                                         peer, 0);
        }
      else
        {
          if (!tp_handle_set_is_member (mixin->local_pending, self_handle))
            break; /* no-op */

          /* promote ourselves to members */
          set = tp_intset_new_containing (self_handle);
          tp_group_mixin_change_members ((GObject *)channel, "",
                                         set,     /* add */
                                         NULL,    /* remove */
                                         NULL,
                                         NULL,
                                         self_handle, 0);
        }

      /* update flags: deny adding and rescinding. Removing the remote peer is
       * still allowed.
       * Removing yourself to end the call is not represented by group flags.
       */
      tp_group_mixin_change_flags ((GObject *)channel, 0,
          TP_CHANNEL_GROUP_FLAG_CAN_ADD | TP_CHANNEL_GROUP_FLAG_CAN_RESCIND);

      break;

    case RAKIA_MEDIA_SESSION_STATE_ENDED:
      set = tp_intset_new ();

      /* remove us and the peer from the member list */
      tp_intset_add (set, self_handle);
      tp_intset_add (set, peer);
      tp_group_mixin_change_members ((GObject *)channel, "",
                                     NULL,      /* add */
                                     set,       /* remove */
                                     NULL,
                                     NULL,
                                     0, 0);

      /* Close the channel; destroy the session first to avoid
       * the rakia_media_session_terminate() path in this case */
      priv_destroy_session (channel);
      rakia_media_channel_close (channel);
      break;
    }

  if (set != NULL)
    tp_intset_destroy (set);
}

void
rakia_media_channel_attach_to_nua_handle (RakiaMediaChannel *self,
                                          nua_handle_t *nh)
{
  RakiaMediaChannelPrivate *priv = RAKIA_MEDIA_CHANNEL_GET_PRIVATE (self);

  rakia_event_target_attach (nh, (GObject *) self);

  /* have the connection handle authentication, before all other
   * response callbacks */
  rakia_base_connection_add_auth_handler (priv->conn, RAKIA_EVENT_TARGET (self));

  g_signal_connect (self,
                    "nua-event::nua_i_invite",
                    G_CALLBACK (priv_nua_i_invite_cb),
                    NULL);
  g_signal_connect (self,
                    "nua-event::nua_i_bye",
                    G_CALLBACK (priv_nua_i_bye_cb),
                    NULL);
  g_signal_connect (self,
                    "nua-event::nua_i_cancel",
                    G_CALLBACK (priv_nua_i_cancel_cb),
                    NULL);
  g_signal_connect (self,
                    "nua-event::nua_i_state",
                    G_CALLBACK (priv_nua_i_state_cb),
                    NULL);

}

/**
 * priv_create_session:
 *
 * Creates a RakiaMediaSession object for given peer.
 **/
static void
priv_create_session (RakiaMediaChannel *channel,
                     nua_handle_t *nh,
                     TpHandle peer)
{
  RakiaMediaChannelPrivate *priv;
  RakiaMediaSession *session;
  TpBaseConnection *conn;
  TpHandleRepoIface *contact_repo;
  gchar *object_path;
  gchar *local_ip_address = NULL;

  DEBUG("enter");

  priv = RAKIA_MEDIA_CHANNEL_GET_PRIVATE (channel);
  conn = (TpBaseConnection *)(priv->conn);
  contact_repo = tp_base_connection_get_handles (conn,
      TP_HANDLE_TYPE_CONTACT);

  g_assert (priv->session == NULL);

  object_path = g_strdup_printf ("%s/MediaSession%u", priv->object_path, peer);

  DEBUG("allocating session, peer=%u", peer);

  /* The channel manages references to the peer handle for the session */
  tp_handle_ref (contact_repo, peer);

  g_object_get (priv->conn,
                "local-ip-address", &local_ip_address,
                NULL);

  session = g_object_new (RAKIA_TYPE_MEDIA_SESSION,
                          "dbus-daemon",
                              tp_base_connection_get_dbus_daemon (conn),
                          "media-channel", channel,
                          "object-path", object_path,
                          "nua-handle", nh,
                          "peer", peer,
                          "local-ip-address", local_ip_address,
                          NULL);

  g_free (local_ip_address);

  g_signal_connect_object (session,
                           "state-changed",
                           G_CALLBACK(priv_session_state_changed_cb),
                           channel,
                           0);
  g_signal_connect_object (session,
                           "dtmf-ready",
                           G_CALLBACK (priv_session_dtmf_ready_cb),
                           channel,
                           0);

  priv->session = session;

  tp_svc_channel_interface_media_signalling_emit_new_session_handler (
      (TpSvcChannelInterfaceMediaSignalling *)channel, object_path, "rtp");

  g_free (object_path);

  DEBUG ("exit");
}

static void
priv_destroy_session(RakiaMediaChannel *channel)
{
  RakiaMediaChannelPrivate *priv = RAKIA_MEDIA_CHANNEL_GET_PRIVATE (channel);
  RakiaMediaSession *session;
  TpBaseConnection *conn;
  TpHandleRepoIface *contact_repo;

  session = priv->session;
  if (session == NULL)
    return;

  DEBUG("enter");

  /* Release the peer handle */
  conn = (TpBaseConnection *)(priv->conn);
  contact_repo = tp_base_connection_get_handles (conn,
      TP_HANDLE_TYPE_CONTACT);
  tp_handle_unref (contact_repo, rakia_media_session_get_peer (session));

  priv->session = NULL;
  g_object_unref (session);

  DEBUG("exit");
}

/*
 * Creates an outbound call session if a session does not exist
 */
static void
priv_outbound_call (RakiaMediaChannel *channel,
                    TpHandle peer)
{
  RakiaMediaChannelPrivate *priv = RAKIA_MEDIA_CHANNEL_GET_PRIVATE (channel);
  nua_handle_t *nh;

  if (priv->session == NULL)
    {
      DEBUG("making outbound call - setting peer handle to %u", peer);

      nh = rakia_base_connection_create_handle (priv->conn, peer);
      priv_create_session (channel, nh, peer);

      /* Bind the channel object to the handle to handle NUA events */
      rakia_media_channel_attach_to_nua_handle (channel, nh);

      nua_handle_unref (nh);
    }
  else
    DEBUG("session already exists");

  g_assert (priv->session != NULL);
}

gboolean
_rakia_media_channel_add_member (GObject *iface,
                                 TpHandle handle,
                                 const gchar *message,
                                 GError **error)
{
  RakiaMediaChannel *self = RAKIA_MEDIA_CHANNEL (iface);
  RakiaMediaChannelPrivate *priv = RAKIA_MEDIA_CHANNEL_GET_PRIVATE (self);
  TpGroupMixin *mixin = TP_GROUP_MIXIN (iface);

  DEBUG("mixin->self_handle=%d, handle=%d", mixin->self_handle, handle);

  if (priv->initiator == mixin->self_handle)
    {
      TpIntSet *remote_pending;

      /* case a: an old-school outbound call
       * (we are the initiator, a new handle added with AddMembers) */

      priv_outbound_call (self, handle);

      /* Backwards compatible behavior:
       * add the peer to remote pending without waiting for the actual request
       * to be sent */
      remote_pending = tp_intset_new_containing (handle);
      tp_group_mixin_change_members (iface,
                                     "",
                                     NULL,    /* add */
                                     NULL,    /* remove */
                                     NULL,    /* local pending */
                                     remote_pending,     /* remote pending */
                                     mixin->self_handle,        /* actor */
                                     TP_CHANNEL_GROUP_CHANGE_REASON_INVITED);
      tp_intset_destroy (remote_pending);

      /* update flags: no more adding.
       * Removal and rescinding are still allowed. */
      tp_group_mixin_change_flags (iface, 0,
          TP_CHANNEL_GROUP_FLAG_CAN_ADD);

      return TRUE;
    }
  if (priv->session &&
      handle == mixin->self_handle &&
      tp_handle_set_is_member (mixin->local_pending, handle))
    {
      /* case b: an incoming invite */
      DEBUG("accepting an incoming invite");
      g_return_val_if_fail (priv->session != NULL, FALSE);

      rakia_media_session_accept (priv->session);

      return TRUE;
    }

  MESSAGE ("unsupported member change requested for a media channel");

  g_set_error (error, TP_ERRORS, TP_ERROR_NOT_AVAILABLE,
      "handle %u cannot be added in the current state", handle);
  return FALSE;
}

static gint
rakia_status_from_tp_reason (TpChannelGroupChangeReason reason)
{
  switch (reason)
    {
    case TP_CHANNEL_GROUP_CHANGE_REASON_NONE:
      return 603;       /* Decline */
    case TP_CHANNEL_GROUP_CHANGE_REASON_NO_ANSWER:
    case TP_CHANNEL_GROUP_CHANGE_REASON_OFFLINE:
      return 480;       /* Temporarily Unavailable */
    case TP_CHANNEL_GROUP_CHANGE_REASON_BUSY:
      return 486;       /* Busy Here */
    case TP_CHANNEL_GROUP_CHANGE_REASON_PERMISSION_DENIED:
    case TP_CHANNEL_GROUP_CHANGE_REASON_BANNED:
      return 403;       /* Forbidden */
    case TP_CHANNEL_GROUP_CHANGE_REASON_INVALID_CONTACT:
      return 404;       /* Not Found */
    default:
      return 500;       /* Server Internal Error */
    }
}

static gboolean
rakia_media_channel_remove_with_reason (GObject *obj,
                                        TpHandle handle,
                                        const gchar *message,
                                        guint reason,
                                        GError **error)
{
  RakiaMediaChannel *self = RAKIA_MEDIA_CHANNEL (obj);
  RakiaMediaChannelPrivate *priv = RAKIA_MEDIA_CHANNEL_GET_PRIVATE (self);
  TpGroupMixin *mixin = TP_GROUP_MIXIN (obj);
  TpIntSet *set = NULL;
  TpHandle self_handle;
  gboolean rejected;

  self_handle = mixin->self_handle;

  if (priv->initiator != self_handle && handle != self_handle)
    {
      g_set_error (error, TP_ERRORS, TP_ERROR_PERMISSION_DENIED,
          "handle %u cannot be removed because you are not the initiator of the"
          " channel", handle);

      return FALSE;
    }

  if (priv->session == NULL)
    {
      g_set_error (error, TP_ERRORS, TP_ERROR_NOT_AVAILABLE,
          "handle %u cannot be removed in the current state", handle);

      return FALSE;
    }

  rejected = (handle == self_handle
      && tp_handle_set_is_member (mixin->local_pending, handle));

  /* We have excluded all the problem cases.
   * Now we always want to remove both members on behalf of the local user */
  set = tp_intset_new ();
  tp_intset_add (set, self_handle);
  tp_intset_add (set, rakia_media_session_get_peer (priv->session));
  tp_group_mixin_change_members (obj, "",
                                 NULL,      /* add */
                                 set,       /* remove */
                                 NULL,
                                 NULL,
                                 self_handle, 0);
  tp_intset_destroy (set);

  if (rejected)
    {
      /* The user has rejected the call */

      gint status;

      status = rakia_status_from_tp_reason (reason);

      /* XXX: raise NotAvailable if it's the wrong state? */
      rakia_media_session_respond (priv->session, status, message);

      /* This session is effectively ended, prevent the nua_i_state handler
       * from useless work */
      rakia_media_session_change_state (priv->session,
                                        RAKIA_MEDIA_SESSION_STATE_ENDED);
    }
  else
    {
      /* Want to terminate the call in whatever other situation;
       * rescinding is handled by sending CANCEL */
      rakia_media_session_terminate (priv->session);
    }

  return TRUE;
}

static void
rakia_media_channel_get_call_states (TpSvcChannelInterfaceCallState *iface,
                                     DBusGMethodInvocation *context)
{
  RakiaMediaChannel *self = RAKIA_MEDIA_CHANNEL (iface);
  RakiaMediaChannelPrivate *priv = RAKIA_MEDIA_CHANNEL_GET_PRIVATE (self);

  tp_svc_channel_interface_call_state_return_from_get_call_states (
        context,
        priv->call_states);
}

static void
rakia_media_channel_get_hold_state (TpSvcChannelInterfaceHold *iface,
                                    DBusGMethodInvocation *context)
{
  RakiaMediaChannel *self = RAKIA_MEDIA_CHANNEL (iface);
  RakiaMediaChannelPrivate *priv = RAKIA_MEDIA_CHANNEL_GET_PRIVATE (self);
  TpLocalHoldState hold_state = TP_LOCAL_HOLD_STATE_UNHELD;
  TpLocalHoldStateReason hold_reason = TP_LOCAL_HOLD_STATE_REASON_NONE;

  if (priv->session == NULL)
    {
      GError e = {TP_ERRORS, TP_ERROR_NOT_AVAILABLE,
                  "The media session is not available"};
      dbus_g_method_return_error (context, &e);
    }

  g_object_get (priv->session,
                "hold-state", &hold_state,
                "hold-state-reason", &hold_reason,
                NULL);

  tp_svc_channel_interface_hold_return_from_get_hold_state (context,
                                                            hold_state,
                                                            hold_reason);
}

static void
rakia_media_channel_request_hold (TpSvcChannelInterfaceHold *iface,
                                  gboolean hold,
                                  DBusGMethodInvocation *context)
{
  RakiaMediaChannel *self = RAKIA_MEDIA_CHANNEL (iface);
  RakiaMediaChannelPrivate *priv;

  priv = RAKIA_MEDIA_CHANNEL_GET_PRIVATE (self);

  if (priv->immutable_streams)
    {
      GError e = {TP_ERRORS, TP_ERROR_NOT_AVAILABLE,
                  "Session modification disabled"};
      dbus_g_method_return_error (context, &e);
      return;
    }
  else if (priv->session != NULL)
    {
      rakia_media_session_request_hold (priv->session, hold);
    }
  else
    {
      GError e = {TP_ERRORS, TP_ERROR_NOT_AVAILABLE,
                  "The media session is not available"};
      dbus_g_method_return_error (context, &e);
      return;
    }

  tp_svc_channel_interface_hold_return_from_request_hold (context);
}

static void
dtmf_player_started_tone_cb (TpDTMFPlayer *dtmf_player,
                             guint event,
                             gpointer user_data)
{
  RakiaMediaChannel *self = user_data;
  RakiaMediaChannelPrivate *priv = self->priv;

  if (priv->session != NULL)
    rakia_media_session_start_telephony_event (priv->session, event);
}

static void
dtmf_player_stopped_tone_cb (TpDTMFPlayer *dtmf_player,
                             gpointer user_data)
{
  RakiaMediaChannel *self = user_data;
  RakiaMediaChannelPrivate *priv = self->priv;

  if (priv->session != NULL)
    rakia_media_session_stop_telephony_event (priv->session);
}

static void
dtmf_player_finished_cb (TpDTMFPlayer *dtmf_player,
                         gboolean cancelled,
                         gpointer user_data)
{
  RakiaMediaChannel *self = user_data;

  tp_svc_channel_interface_dtmf_emit_stopped_tones (self, cancelled);
}

static void
dtmf_player_tones_deferred_cb (TpDTMFPlayer *dtmf_player,
                               gchar *tones,
                               gpointer user_data)
{
  RakiaMediaChannel *self = user_data;
  RakiaMediaChannelPrivate *priv = self->priv;

  g_free (priv->deferred_tones);
  priv->deferred_tones = g_strdup (tones);

  tp_svc_channel_interface_dtmf_emit_tones_deferred (self, tones);
}

static void
priv_ensure_dtmf_player (RakiaMediaChannel *self)
{
  RakiaMediaChannelPrivate *priv = self->priv;
  if (priv->dtmf_player != NULL)
    return;

  priv->dtmf_player = tp_dtmf_player_new ();

  g_signal_connect (priv->dtmf_player, "started-tone",
      G_CALLBACK (dtmf_player_started_tone_cb), self);
  g_signal_connect (priv->dtmf_player, "stopped-tone",
      G_CALLBACK (dtmf_player_stopped_tone_cb), self);
  g_signal_connect (priv->dtmf_player, "finished",
      G_CALLBACK (dtmf_player_finished_cb), self);
  g_signal_connect (priv->dtmf_player, "tones-deferred",
      G_CALLBACK (dtmf_player_tones_deferred_cb), self);
}

static gboolean
rakia_media_channel_send_dtmf_tones (RakiaMediaChannel *self,
                                     const gchar *tones,
                                     guint tone_duration,
                                     GError **error)
{
  RakiaMediaChannelPrivate *priv = self->priv;

  /* Perform sanity checks on the session */
  if (priv->session == NULL)
    {
      g_set_error (error, TP_ERRORS, TP_ERROR_NOT_AVAILABLE,
          "the media session is not available, has the channel been closed?");
      return FALSE;
    }
  if (!rakia_media_session_has_media (priv->session,
          TP_MEDIA_STREAM_TYPE_AUDIO))
    {
      g_set_error (error, TP_ERRORS, TP_ERROR_NOT_AVAILABLE,
          "no audio streams are available");
      return FALSE;
    }

  priv_ensure_dtmf_player (self);

  if (!tp_dtmf_player_play (priv->dtmf_player, tones, tone_duration,
          RAKIA_DTMF_GAP_DURATION, RAKIA_DTMF_PAUSE_DURATION, error))
    return FALSE;

  g_free (priv->deferred_tones);
  priv->deferred_tones = NULL;

  tp_svc_channel_interface_dtmf_emit_sending_tones (self, tones);

  return TRUE;
}

static void
rakia_media_channel_start_tone (TpSvcChannelInterfaceDTMF *iface,
                                guint stream_id,
                                guchar event,
                                DBusGMethodInvocation *context)
{
  RakiaMediaChannel *self = RAKIA_MEDIA_CHANNEL (iface);
  GError *error = NULL;
  gchar tone[2];

  DEBUG("enter");

  if (event >= NUM_TP_DTMF_EVENTS)
    {
      g_set_error (&error, TP_ERRORS, TP_ERROR_INVALID_ARGUMENT,
                   "event %u is not a known DTMF event", event);
      dbus_g_method_return_error (context, error);
      g_error_free (error);
      return;
    }

  tone[0] = tp_dtmf_event_to_char (event);
  tone[1] = '\0';

  if (!rakia_media_channel_send_dtmf_tones (self, tone, G_MAXUINT, &error))
    {
      dbus_g_method_return_error (context, error);
      g_error_free (error);
      return;
    }

  tp_svc_channel_interface_dtmf_return_from_start_tone (context);
}

static void
rakia_media_channel_stop_tone (TpSvcChannelInterfaceDTMF *iface,
                               guint stream_id,
                               DBusGMethodInvocation *context)
{
  RakiaMediaChannel *self = RAKIA_MEDIA_CHANNEL (iface);
  RakiaMediaChannelPrivate *priv;

  DEBUG("enter");

  priv = RAKIA_MEDIA_CHANNEL_GET_PRIVATE (self);

  if (priv->dtmf_player != NULL)
    tp_dtmf_player_cancel (priv->dtmf_player);

  tp_svc_channel_interface_dtmf_return_from_stop_tone (context);
}

static void
rakia_media_channel_multiple_tones (TpSvcChannelInterfaceDTMF *iface,
                                    const gchar *tones,
                                    DBusGMethodInvocation *context)
{
  RakiaMediaChannel *self = (RakiaMediaChannel *) iface;
  GError *error = NULL;

  if (!rakia_media_channel_send_dtmf_tones (self, tones,
          RAKIA_DTMF_TONE_DURATION, &error))
    {
      dbus_g_method_return_error (context, error);
      g_error_free (error);
      return;
    }

  tp_svc_channel_interface_dtmf_return_from_multiple_tones (context);
}

static void
priv_session_dtmf_ready_cb (RakiaMediaSession *session,
                            RakiaMediaChannel *channel)
{
  RakiaMediaChannelPrivate *priv = channel->priv;
  if (!tp_str_empty (priv->initial_tones))
    rakia_media_channel_send_dtmf_tones (channel, priv->initial_tones,
        RAKIA_DTMF_TONE_DURATION, NULL);
}

static void
event_target_init(gpointer g_iface, gpointer iface_data)
{
}

static void
channel_iface_init(gpointer g_iface, gpointer iface_data)
{
  TpSvcChannelClass *klass = (TpSvcChannelClass *)g_iface;

  tp_svc_channel_implement_close (
      klass, rakia_media_channel_dbus_close);
#define IMPLEMENT(x) tp_svc_channel_implement_##x (\
      klass, rakia_media_channel_##x)
  IMPLEMENT(get_channel_type);
  IMPLEMENT(get_handle);
  IMPLEMENT(get_interfaces);
#undef IMPLEMENT
}

static void
streamed_media_iface_init(gpointer g_iface, gpointer iface_data)
{
  TpSvcChannelTypeStreamedMediaClass *klass = (TpSvcChannelTypeStreamedMediaClass *)g_iface;

#define IMPLEMENT(x) tp_svc_channel_type_streamed_media_implement_##x (\
    klass, rakia_media_channel_##x)
  IMPLEMENT(list_streams);
  IMPLEMENT(remove_streams);
  IMPLEMENT(request_stream_direction);
  IMPLEMENT(request_streams);
#undef IMPLEMENT
}

static void
media_signalling_iface_init(gpointer g_iface, gpointer iface_data)
{
  TpSvcChannelInterfaceMediaSignallingClass *klass = (TpSvcChannelInterfaceMediaSignallingClass *)g_iface;

#define IMPLEMENT(x) tp_svc_channel_interface_media_signalling_implement_##x (\
    klass, rakia_media_channel_##x)
  IMPLEMENT(get_session_handlers);
#undef IMPLEMENT
}

static void
dtmf_iface_init (gpointer g_iface, gpointer iface_data)
{
  TpSvcChannelInterfaceDTMFClass *klass = (TpSvcChannelInterfaceDTMFClass *)g_iface;

#define IMPLEMENT(x) tp_svc_channel_interface_dtmf_implement_##x (\
    klass, rakia_media_channel_##x)
  IMPLEMENT(start_tone);
  IMPLEMENT(stop_tone);
  IMPLEMENT(multiple_tones);
#undef IMPLEMENT
}

static void
call_state_iface_init (gpointer g_iface,
                       gpointer iface_data)
{
  TpSvcChannelInterfaceCallStateClass *klass = g_iface;
#define IMPLEMENT(x) tp_svc_channel_interface_call_state_implement_##x (\
    klass, rakia_media_channel_##x)
  IMPLEMENT (get_call_states);
#undef IMPLEMENT
}

static void
hold_iface_init (gpointer g_iface,
                 gpointer iface_data)
{
  TpSvcChannelInterfaceHoldClass *klass = g_iface;

#define IMPLEMENT(x) tp_svc_channel_interface_hold_implement_##x (\
    klass, rakia_media_channel_##x)
  IMPLEMENT (get_hold_state);
  IMPLEMENT (request_hold);
#undef IMPLEMENT
}