summaryrefslogtreecommitdiff
path: root/src/sip-media-session.c
blob: 82722001f940acf937583cbbe340a5482be77124 (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
/*
 * sip-media-session.c - Source for TpsipMediaSession
 * Copyright (C) 2005 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-session).
 *   @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 <dbus/dbus-glib.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>

#include <sofia-sip/sip_status.h>

#include <telepathy-glib/dbus.h>
#include <telepathy-glib/errors.h>
#include <telepathy-glib/gtypes.h>
#include <telepathy-glib/interfaces.h>
#include <telepathy-glib/svc-media-interfaces.h>

#include "config.h"

#include "sip-media-session.h"
#include "sip-media-channel.h"
#include "sip-media-stream.h"
#include "sip-connection-helpers.h"
#include "signals-marshal.h"

#define DEBUG_FLAG TPSIP_DEBUG_MEDIA
#include "debug.h"

/* The timeout for outstanding re-INVITE transactions in seconds.
 * Chosen to match the allowed cancellation timeout for proxies
 * described in RFC 3261 Section 13.3.1.1 */
#define TPSIP_REINVITE_TIMEOUT 180

static void session_handler_iface_init (gpointer, gpointer);

G_DEFINE_TYPE_WITH_CODE(TpsipMediaSession,
    tpsip_media_session,
    G_TYPE_OBJECT,
    G_IMPLEMENT_INTERFACE (TP_TYPE_SVC_MEDIA_SESSION_HANDLER,
      session_handler_iface_init)
    )

/* signal enum */
enum
{
  SIG_STATE_CHANGED,
  SIG_LAST_SIGNAL
};

/* properties */
enum
{
  PROP_MEDIA_CHANNEL = 1,
  PROP_DBUS_DAEMON,
  PROP_OBJECT_PATH,
  PROP_NUA_OP,
  PROP_PEER,
  PROP_HOLD_STATE,
  PROP_HOLD_STATE_REASON,
  PROP_REMOTE_PTIME,
  PROP_REMOTE_MAX_PTIME,
  PROP_RTCP_ENABLED,
  PROP_LOCAL_IP_ADDRESS,
  PROP_STUN_SERVERS,
  LAST_PROPERTY
};

static guint signals[SIG_LAST_SIGNAL] = {0};

#ifdef ENABLE_DEBUG

/**
 * Media session states:
 * - created, objects created, local cand/codec query ongoing
 * - invite-sent, an INVITE with local SDP sent, awaiting response
 * - invite-received, a remote INVITE received, response is pending
 * - response-received, a 200 OK received, codec intersection is in progress
 * - active, codecs and candidate pairs have been negotiated (note,
 *   SteamEngine might still fail to verify connectivity and report
 *   an error)
 * - reinvite-sent, a local re-INVITE sent, response is pending
 * - reinvite-received, a remote re-INVITE received, response is pending
 * - ended, session has ended
 */
static const char* session_states[] =
{
    "created",
    "invite-sent",
    "invite-received",
    "response-received",
    "active",
    "reinvite-sent",
    "reinvite-received",
    "reinvite-pending",
    "ended"
};

#endif /* ENABLE_DEBUG */

/* private structure */
typedef struct _TpsipMediaSessionPrivate TpsipMediaSessionPrivate;

struct _TpsipMediaSessionPrivate
{
  TpDBusDaemon *dbus_daemon;
  TpsipMediaChannel *channel;             /* see gobj. prop. 'media-channel' */
  gchar *object_path;                     /* see gobj. prop. 'object-path' */
  nua_handle_t *nua_op;                   /* see gobj. prop. 'nua-handle' */
  TpHandle peer;                          /* see gobj. prop. 'peer' */
  gchar *local_ip_address;                /* see gobj. prop. 'local-ip-address' */
  gchar *remote_ptime;                    /* see gobj. prop. 'remote-ptime' */
  gchar *remote_max_ptime;                /* see gobj. prop. 'remote-max-ptime' */
  gboolean rtcp_enabled;                  /* see gobj. prop. 'rtcp-enabled' */
  TpsipMediaSessionState state;           /* session state */
  TpLocalHoldState hold_state;         /* local hold state aggregated from stream directions */
  TpLocalHoldStateReason hold_reason;  /* last used hold state change reason */
  nua_saved_event_t saved_event[1];       /* Saved incoming request event */
  gint local_non_ready;                   /* number of streams with local information update pending */
  guint remote_stream_count;              /* number of streams last seen in a remote offer */
  guint glare_timer_id;
  su_home_t *home;                        /* Sofia memory home for remote SDP session structure */
  su_home_t *backup_home;                 /* Sofia memory home for previous generation remote SDP session*/
  sdp_session_t *remote_sdp;              /* last received remote session */
  sdp_session_t *backup_remote_sdp;       /* previous remote session */
  GPtrArray *streams;
  gboolean remote_initiated;              /*< session is remotely intiated */
  gboolean accepted;                      /*< session has been locally accepted for use */
  gboolean se_ready;                      /*< connection established with stream-engine */
  gboolean pending_offer;                 /*< local media have been changed, but a re-INVITE is pending */
  gboolean dispose_has_run;
};

#define TPSIP_MEDIA_SESSION_GET_PRIVATE(o)     (G_TYPE_INSTANCE_GET_PRIVATE ((o), TPSIP_TYPE_MEDIA_SESSION, TpsipMediaSessionPrivate))

static void tpsip_media_session_get_property (GObject    *object,
					    guint       property_id,
					    GValue     *value,
					    GParamSpec *pspec);
static void tpsip_media_session_set_property (GObject      *object,
					    guint         property_id,
					    const GValue *value,
					    GParamSpec   *pspec);

static TpsipMediaStream *
tpsip_media_session_get_stream (TpsipMediaSession *self,
                              guint stream_id,
                              GError **error);

static void priv_request_response_step (TpsipMediaSession *session);
static void priv_session_invite (TpsipMediaSession *session, gboolean reinvite);
static void priv_local_media_changed (TpsipMediaSession *session);
static gboolean priv_update_remote_media (TpsipMediaSession *session,
                                          gboolean authoritative);
static void priv_save_event (TpsipMediaSession *self);
static void priv_zap_event (TpsipMediaSession *self);

static void tpsip_media_session_init (TpsipMediaSession *obj)
{
  TpsipMediaSessionPrivate *priv = TPSIP_MEDIA_SESSION_GET_PRIVATE (obj);

  priv->state = TPSIP_MEDIA_SESSION_STATE_CREATED;
  priv->hold_state = TP_LOCAL_HOLD_STATE_UNHELD;
  priv->hold_reason = TP_LOCAL_HOLD_STATE_REASON_NONE;
  priv->rtcp_enabled = TRUE;

  /* allocate any data required by the object here */
  priv->streams = g_ptr_array_new ();
}

static GObject *
tpsip_media_session_constructor (GType type, guint n_props,
			       GObjectConstructParam *props)
{
  GObject *obj;
  TpsipMediaSessionPrivate *priv;

  obj = G_OBJECT_CLASS (tpsip_media_session_parent_class)->
           constructor (type, n_props, props);
  priv = TPSIP_MEDIA_SESSION_GET_PRIVATE (TPSIP_MEDIA_SESSION (obj));

  g_assert (TP_IS_DBUS_DAEMON (priv->dbus_daemon));
  tp_dbus_daemon_register_object (priv->dbus_daemon, priv->object_path, obj);

  return obj;
}

static void tpsip_media_session_get_property (GObject    *object,
					    guint       property_id,
					    GValue     *value,
					    GParamSpec *pspec)
{
  TpsipMediaSession *session = TPSIP_MEDIA_SESSION (object);
  TpsipMediaSessionPrivate *priv = TPSIP_MEDIA_SESSION_GET_PRIVATE (session);

  switch (property_id)
    {
    case PROP_DBUS_DAEMON:
      g_value_set_object (value, priv->dbus_daemon);
      break;
    case PROP_MEDIA_CHANNEL:
      g_value_set_object (value, priv->channel);
      break;
    case PROP_OBJECT_PATH:
      g_value_set_string (value, priv->object_path);
      break;
    case PROP_NUA_OP:
      g_value_set_pointer (value, priv->nua_op);
      break;
    case PROP_PEER:
      g_value_set_uint (value, priv->peer);
      break;
    case PROP_HOLD_STATE:
      g_value_set_uint (value, priv->hold_state);
      break;
    case PROP_HOLD_STATE_REASON:
      g_value_set_uint (value, priv->hold_reason);
      break;
    case PROP_REMOTE_PTIME:
      g_value_set_string (value, priv->remote_ptime);
      break;
    case PROP_REMOTE_MAX_PTIME:
      g_value_set_string (value, priv->remote_max_ptime);
      break;
    case PROP_LOCAL_IP_ADDRESS:
      g_value_set_string (value, priv->local_ip_address);
      break;
    case PROP_RTCP_ENABLED:
      g_value_set_boolean (value, priv->rtcp_enabled);
      break;
    case PROP_STUN_SERVERS:
      {
        /* TODO: should be able to get all entries from the DNS lookup(s).
         * At the moment, rawudp ignores all servers except the first one. */
        GPtrArray *servers;
        gchar *stun_server = NULL;
        guint stun_port = TPSIP_DEFAULT_STUN_PORT;

        g_return_if_fail (priv->channel != NULL);

        g_object_get (priv->channel,
            "stun-server", &stun_server,
            "stun-port", &stun_port,
            NULL);

        servers = g_ptr_array_new ();

        if (stun_server != NULL)
          {
            GValue addr = { 0 };
            const GType addr_type = TP_STRUCT_TYPE_SOCKET_ADDRESS_IP;

            g_value_init (&addr, addr_type);
            g_value_take_boxed (&addr,
                dbus_g_type_specialized_construct (addr_type));

            dbus_g_type_struct_set (&addr,
                0, stun_server,
                1, (guint16) stun_port,
                G_MAXUINT);

            g_ptr_array_add (servers, g_value_get_boxed (&addr));

            g_free (stun_server);
          }

        g_value_take_boxed (value, servers);
      }
      break;
    default:
      G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec);
      break;
  }
}

static void tpsip_media_session_set_property (GObject      *object,
					    guint         property_id,
					    const GValue *value,
					    GParamSpec   *pspec)
{
  TpsipMediaSession *session = TPSIP_MEDIA_SESSION (object);
  TpsipMediaSessionPrivate *priv = TPSIP_MEDIA_SESSION_GET_PRIVATE (session);

  switch (property_id)
    {
    case PROP_DBUS_DAEMON:
      g_assert (priv->dbus_daemon == NULL);       /* construct-only */
      priv->dbus_daemon = g_value_dup_object (value);
      break;
    case PROP_MEDIA_CHANNEL:
      priv->channel = TPSIP_MEDIA_CHANNEL (g_value_get_object (value));
      break;
    case PROP_OBJECT_PATH:
      g_assert (priv->object_path == NULL);
      priv->object_path = g_value_dup_string (value);
      break;
    case PROP_NUA_OP:
      /* you can only set the NUA handle once - migrating a media session
       * between two NUA handles makes no sense */
      g_return_if_fail (priv->nua_op == NULL);
      priv->nua_op = g_value_get_pointer (value);
      nua_handle_ref (priv->nua_op);
      break;
    case PROP_PEER:
      priv->peer = g_value_get_uint (value);
      break;
    case PROP_LOCAL_IP_ADDRESS:
      g_assert (priv->local_ip_address == NULL);
      priv->local_ip_address = g_value_dup_string (value);
      break;
    default:
      G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec);
      break;
  }
}

static void tpsip_media_session_dispose (GObject *object);
static void tpsip_media_session_finalize (GObject *object);

static void
tpsip_media_session_class_init (TpsipMediaSessionClass *klass)
{
  GObjectClass *object_class = G_OBJECT_CLASS (klass);
  GParamSpec *param_spec;

  g_type_class_add_private (klass, sizeof (TpsipMediaSessionPrivate));

  object_class->constructor = tpsip_media_session_constructor;

  object_class->get_property = tpsip_media_session_get_property;
  object_class->set_property = tpsip_media_session_set_property;

  object_class->dispose = tpsip_media_session_dispose;
  object_class->finalize = tpsip_media_session_finalize;

  param_spec = g_param_spec_object ("dbus-daemon", "TpDBusDaemon",
      "Connection to D-Bus.", TP_TYPE_DBUS_DAEMON,
      G_PARAM_CONSTRUCT_ONLY | G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS);
  g_object_class_install_property (object_class, PROP_DBUS_DAEMON, param_spec);

  param_spec = g_param_spec_object ("media-channel", "TpsipMediaChannel object",
      "SIP media channel object that owns this media session object"
      " (not reference counted).",
      TPSIP_TYPE_MEDIA_CHANNEL,
      G_PARAM_CONSTRUCT_ONLY | G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS);
  g_object_class_install_property (object_class, PROP_MEDIA_CHANNEL, param_spec);

  param_spec = g_param_spec_string ("object-path", "D-Bus object path",
      "The D-Bus object path used for this object on the bus.",
      NULL,
      G_PARAM_CONSTRUCT_ONLY | G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS);
  g_object_class_install_property (object_class, PROP_OBJECT_PATH, param_spec);

  param_spec = g_param_spec_pointer ("nua-handle", "NUA handle",
      "NUA stack operation handle associated with this media session.",
      G_PARAM_CONSTRUCT_ONLY | G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS);
  g_object_class_install_property (object_class, PROP_NUA_OP, param_spec);

  param_spec = g_param_spec_uint ("peer", "Session peer",
      "The TpHandle representing the contact with whom this session communicates.",
      0, G_MAXUINT32,
      0,
      G_PARAM_CONSTRUCT_ONLY | G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS);
  g_object_class_install_property (object_class, PROP_PEER, param_spec);

  param_spec = g_param_spec_uint ("hold-state", "Local hold state",
      "The current Local_Hold_State value as reported by the Hold interface",
      TP_LOCAL_HOLD_STATE_UNHELD, TP_LOCAL_HOLD_STATE_PENDING_UNHOLD,
      TP_LOCAL_HOLD_STATE_UNHELD,
      G_PARAM_READABLE | G_PARAM_STATIC_STRINGS);
  g_object_class_install_property (object_class, PROP_HOLD_STATE, param_spec);

  param_spec = g_param_spec_uint ("hold-state-reason",
      "Local hold state change reason",
      "The last Local_Hold_State_Reason value as reported by the Hold interface",
      TP_LOCAL_HOLD_STATE_REASON_NONE,
      TP_LOCAL_HOLD_STATE_REASON_RESOURCE_NOT_AVAILABLE,
      TP_LOCAL_HOLD_STATE_REASON_NONE,
      G_PARAM_READABLE | G_PARAM_STATIC_STRINGS);
  g_object_class_install_property (object_class, PROP_HOLD_STATE_REASON, param_spec);

  param_spec = g_param_spec_string ("remote-ptime",
      "a=ptime value of remote media session",
      "Value of the a=ptime attribute of the remote media session, or NULL",
      NULL,
      G_PARAM_READABLE | G_PARAM_STATIC_STRINGS);
  g_object_class_install_property (object_class, PROP_REMOTE_PTIME, param_spec);

  param_spec = g_param_spec_string ("remote-max-ptime",
      "a=maxptime value of remote media session",
      "Value of the a=maxptime attribute of the remote media session, or NULL",
      NULL,
      G_PARAM_READABLE | G_PARAM_STATIC_STRINGS);
  g_object_class_install_property (object_class, PROP_REMOTE_MAX_PTIME, param_spec);

  param_spec = g_param_spec_string ("local-ip-address", "Local IP address",
      "The local IP address preferred for media streams",
      NULL,
      G_PARAM_CONSTRUCT_ONLY | G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS);
  g_object_class_install_property (object_class, PROP_LOCAL_IP_ADDRESS, param_spec);

  param_spec = g_param_spec_boolean ("rtcp-enabled", "RTCP enabled",
      "Is RTCP enabled session-wide",
      TRUE,
      G_PARAM_READABLE | G_PARAM_STATIC_STRINGS);
  g_object_class_install_property (object_class, PROP_RTCP_ENABLED, param_spec);

  param_spec = g_param_spec_boxed ("stun-servers", "STUN servers",
      "Array of IP address-port pairs for available STUN servers",
      TP_ARRAY_TYPE_SOCKET_ADDRESS_IP_LIST,
      G_PARAM_READABLE | G_PARAM_STATIC_STRINGS);
  g_object_class_install_property (object_class, PROP_STUN_SERVERS, param_spec);

  signals[SIG_STATE_CHANGED] =
    g_signal_new ("state-changed",
                  G_OBJECT_CLASS_TYPE (klass),
                  G_SIGNAL_RUN_LAST | G_SIGNAL_DETAILED,
                  0,
                  NULL, NULL,
                  _tpsip_marshal_VOID__UINT_UINT,
                  G_TYPE_NONE, 2, G_TYPE_UINT, G_TYPE_UINT);
}

static void
tpsip_media_session_dispose (GObject *object)
{
  TpsipMediaSession *self = TPSIP_MEDIA_SESSION (object);
  TpsipMediaSessionPrivate *priv = TPSIP_MEDIA_SESSION_GET_PRIVATE (self);

  if (priv->dispose_has_run)
    return;

  DEBUG("enter");

  priv->dispose_has_run = TRUE;

  if (priv->glare_timer_id)
    g_source_remove (priv->glare_timer_id);

  tp_clear_object (&priv->dbus_daemon);

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

  DEBUG("exit");
}

static void
tpsip_media_session_finalize (GObject *object)
{
  TpsipMediaSession *self = TPSIP_MEDIA_SESSION (object);
  TpsipMediaSessionPrivate *priv = TPSIP_MEDIA_SESSION_GET_PRIVATE (self);
  guint i;

  /* terminating the session should have discarded the NUA handle */
  g_assert (priv->nua_op == NULL);

  /* free any data held directly by the object here */

  for (i = 0; i < priv->streams->len; i++) {
    TpsipMediaStream *stream = g_ptr_array_index (priv->streams, i);
    if (stream != NULL)
      {
        WARNING ("stream %u (%p) left over, reaping", i, stream);
        g_object_unref (stream);
      }
  }
  g_ptr_array_free(priv->streams, TRUE);

  priv_zap_event (self);

  if (priv->home != NULL)
    su_home_unref (priv->home);
  if (priv->backup_home != NULL)
    su_home_unref (priv->backup_home);

  g_free (priv->remote_ptime);
  g_free (priv->remote_max_ptime);
  g_free (priv->local_ip_address);
  g_free (priv->object_path);

  G_OBJECT_CLASS (tpsip_media_session_parent_class)->finalize (object);

  DEBUG("exit");
}



/**
 * tpsip_media_session_error
 *
 * Implements DBus method Error
 * on interface org.freedesktop.Telepathy.Media.SessionHandler
 */
static void
tpsip_media_session_error (TpSvcMediaSessionHandler *iface,
                         guint errno,
                         const gchar *message,
                         DBusGMethodInvocation *context)
{
  TpsipMediaSession *obj = TPSIP_MEDIA_SESSION (iface);

  SESSION_DEBUG (obj, "Media.SessionHandler::Error called (%s), terminating session", message);

  tpsip_media_session_terminate (obj);

  tp_svc_media_session_handler_return_from_error (context);
}

static void priv_emit_new_stream (TpsipMediaSession *self,
				  TpsipMediaStream *stream)
{
  gchar *object_path;
  guint id;
  guint media_type;
  guint direction;

  g_object_get (stream,
                "object-path", &object_path,
                "id", &id,
                "media-type", &media_type,
                "direction", &direction,
                NULL);

  /* note: all of the streams are bidirectional from farsight's point of view, it's
   * just in the signalling they change */

  tp_svc_media_session_handler_emit_new_stream_handler (
      (TpSvcMediaSessionHandler *)self, object_path, id, media_type,
      direction);

  g_free (object_path);
}


/**
 * tpsip_media_session_ready
 *
 * Implements DBus method Ready
 * on interface org.freedesktop.Telepathy.Media.SessionHandler
 */
static void
tpsip_media_session_ready (TpSvcMediaSessionHandler *iface,
                         DBusGMethodInvocation *context)
{
  TpsipMediaSession *obj = TPSIP_MEDIA_SESSION (iface);
  TpsipMediaSessionPrivate *priv;
  guint i;

  DEBUG ("enter");

  priv = TPSIP_MEDIA_SESSION_GET_PRIVATE (obj);

  if (!priv->se_ready)
    {
      priv->se_ready = TRUE;

      /* note: streams are generated in priv_create_media_stream() */

      for (i = 0; i < priv->streams->len; i++)
        {
          TpsipMediaStream *stream = g_ptr_array_index (priv->streams, i);
          if (stream)
            priv_emit_new_stream (obj, stream);
        }
    }
  
  tp_svc_media_session_handler_return_from_ready (context);
}

/***********************************************************************
 * Helper functions follow (not based on generated templates)
 ***********************************************************************/

TpHandle
tpsip_media_session_get_peer (TpsipMediaSession *session)
{
  TpsipMediaSessionPrivate *priv = TPSIP_MEDIA_SESSION_GET_PRIVATE (session);
  return priv->peer;
}

TpsipMediaSessionState
tpsip_media_session_get_state (TpsipMediaSession *session)
{
  TpsipMediaSessionPrivate *priv = TPSIP_MEDIA_SESSION_GET_PRIVATE (session);
  return priv->state;
}

static gboolean
tpsip_media_session_supports_media_type (guint media_type)
{
  switch (media_type)
    {
    case TP_MEDIA_STREAM_TYPE_AUDIO:
    case TP_MEDIA_STREAM_TYPE_VIDEO:
      return TRUE;
    }
  return FALSE;
}

static void
priv_close_all_streams (TpsipMediaSession *session)
{
  TpsipMediaSessionPrivate *priv = TPSIP_MEDIA_SESSION_GET_PRIVATE (session);
  guint i;
  for (i = 0; i < priv->streams->len; i++)
    {
      TpsipMediaStream *stream;
      stream = g_ptr_array_index (priv->streams, i);
      if (stream != NULL)
        tpsip_media_stream_close (stream);
      g_assert (g_ptr_array_index (priv->streams, i) == NULL);
    }
}

static void
priv_apply_streams_pending_direction (TpsipMediaSession *session,
                                      guint pending_send_mask)
{
  TpsipMediaSessionPrivate *priv = TPSIP_MEDIA_SESSION_GET_PRIVATE (session);
  TpsipMediaStream *stream;
  guint i;

  /* If there has been a local change pending a re-INVITE,
   * suspend remote approval until the next transaction */
  if (priv->pending_offer)
    pending_send_mask &= ~(guint)TP_MEDIA_STREAM_PENDING_REMOTE_SEND;

  /* Apply the pending direction changes */
  for (i = 0; i < priv->streams->len; i++)
    {
      stream = g_ptr_array_index(priv->streams, i);
      if (stream != NULL)
        tpsip_media_stream_apply_pending_direction (stream, pending_send_mask);
    }
}

void
tpsip_media_session_change_state (TpsipMediaSession *session,
                                TpsipMediaSessionState new_state)
{
  TpsipMediaSessionPrivate *priv = TPSIP_MEDIA_SESSION_GET_PRIVATE (session);
  guint old_state;

  if (priv->state == new_state)
    return;

  old_state = priv->state;
  priv->state = new_state;

  SESSION_DEBUG (session, "state change: %s -> %s",
      session_states[old_state],
      session_states[new_state]);

  switch (new_state)
    {
    case TPSIP_MEDIA_SESSION_STATE_CREATED:
    case TPSIP_MEDIA_SESSION_STATE_INVITE_RECEIVED:
    case TPSIP_MEDIA_SESSION_STATE_REINVITE_RECEIVED:
    case TPSIP_MEDIA_SESSION_STATE_INVITE_SENT:
    case TPSIP_MEDIA_SESSION_STATE_REINVITE_SENT:
    case TPSIP_MEDIA_SESSION_STATE_RESPONSE_RECEIVED:
    case TPSIP_MEDIA_SESSION_STATE_REINVITE_PENDING:
      break;
    case TPSIP_MEDIA_SESSION_STATE_ACTIVE:
      /* Apply any pending remote send after outgoing INVITEs.
       * We don't want automatic removal of pending local send after
       * responding to incoming re-INVITEs, however */
      priv_apply_streams_pending_direction (session,
          TP_MEDIA_STREAM_PENDING_REMOTE_SEND);
      break;
    case TPSIP_MEDIA_SESSION_STATE_ENDED:
      priv_close_all_streams (session);
      DEBUG("destroying the NUA handle %p", priv->nua_op);
      if (priv->nua_op != NULL)
        {
          nua_handle_destroy (priv->nua_op);
          priv->nua_op = NULL;
        }
      break;

      /* Don't add default because we want to be warned by the compiler
       * about unhandled states */
    }

  g_signal_emit (session, signals[SIG_STATE_CHANGED], 0, old_state, new_state);

  if (new_state == TPSIP_MEDIA_SESSION_STATE_ACTIVE && priv->pending_offer)
    priv_session_invite (session, TRUE);
}

#ifdef ENABLE_DEBUG
void
tpsip_media_session_debug (TpsipMediaSession *session,
                           const gchar *format, ...)
{
  TpsipMediaSessionPrivate *priv;
  va_list list;
  gchar buf[240];

  if (!tpsip_debug_flag_is_set (DEBUG_FLAG))
    return;

  priv = TPSIP_MEDIA_SESSION_GET_PRIVATE (session);

  va_start (list, format);

  g_vsnprintf (buf, sizeof (buf), format, list);

  va_end (list);

  DEBUG ("SIP media session [%-17s]: %s",
      session_states[priv->state], buf);
}
#endif /* ENABLE_DEBUG */

void tpsip_media_session_terminate (TpsipMediaSession *session)
{
  TpsipMediaSessionPrivate *priv = TPSIP_MEDIA_SESSION_GET_PRIVATE (session);

  DEBUG ("enter");

  if (priv->state == TPSIP_MEDIA_SESSION_STATE_ENDED)
    return;

  /* XXX: taken care of by the state change? */
  priv_close_all_streams (session);

  if (priv->nua_op != NULL)
    {
      /* XXX: should the stack do pretty much the same
       * (except freeing the saved event) upon nua_handle_destroy()? */
      switch (priv->state)
        {
        case TPSIP_MEDIA_SESSION_STATE_ACTIVE:
        case TPSIP_MEDIA_SESSION_STATE_RESPONSE_RECEIVED:
        case TPSIP_MEDIA_SESSION_STATE_REINVITE_SENT:
        case TPSIP_MEDIA_SESSION_STATE_REINVITE_PENDING:
          DEBUG("sending BYE");
          nua_bye (priv->nua_op, TAG_END());
          break;
        case TPSIP_MEDIA_SESSION_STATE_INVITE_SENT:
          DEBUG("sending CANCEL");
          nua_cancel (priv->nua_op, TAG_END());
          break;
        case TPSIP_MEDIA_SESSION_STATE_INVITE_RECEIVED:
          DEBUG("sending the 480 response to an incoming INVITE");
          nua_respond (priv->nua_op, 480, "Terminated", TAG_END());
          break;
        case TPSIP_MEDIA_SESSION_STATE_REINVITE_RECEIVED:
          if (priv->saved_event[0])
            {
              DEBUG("sending the 480 response to an incoming re-INVITE");
              nua_respond (priv->nua_op, 480, "Terminated",
                           NUTAG_WITH(nua_saved_event_request (priv->saved_event)),
                           TAG_END());
              nua_destroy_event (priv->saved_event);
            }
          DEBUG("sending BYE to terminate the call itself");
          nua_bye (priv->nua_op, TAG_END());
          break;
        default:
          /* let the Sofia stack decide what do to */;
        }
    }

  tpsip_media_session_change_state (session, TPSIP_MEDIA_SESSION_STATE_ENDED);
}

gboolean
tpsip_media_session_set_remote_media (TpsipMediaSession *session,
                                    const sdp_session_t* sdp)
{
  TpsipMediaSessionPrivate *priv = TPSIP_MEDIA_SESSION_GET_PRIVATE (session);
  gboolean authoritative;

  DEBUG ("enter");

  if (priv->state == TPSIP_MEDIA_SESSION_STATE_INVITE_SENT
      || priv->state == TPSIP_MEDIA_SESSION_STATE_REINVITE_SENT)
    {
      tpsip_media_session_change_state (
                session,
                TPSIP_MEDIA_SESSION_STATE_RESPONSE_RECEIVED);
    }
  else
    {
      /* Remember the m= line count in the remote offer,
       * to match it with exactly this number of answer lines */
      sdp_media_t *media;
      guint count = 0;

      for (media = sdp->sdp_media; media != NULL; media = media->m_next)
        ++count;

      priv->remote_stream_count = count;
    }

  /* Shortcut session non-updates */
  if (!sdp_session_cmp (priv->remote_sdp, sdp))
    goto finally;

  /* Delete a backup session structure, if any */
  if (priv->backup_remote_sdp != NULL)
    {
      priv->backup_remote_sdp = NULL;
      g_assert (priv->backup_home != NULL);
      su_home_unref (priv->backup_home);
      priv->backup_home = NULL;
    }
  /* Back up the old session.
   * The streams still need the old media descriptions */
  if (priv->remote_sdp != NULL)
    {
      g_assert (priv->home != NULL);
      g_assert (priv->backup_home == NULL);
      priv->backup_home = priv->home;
      priv->backup_remote_sdp = priv->remote_sdp;
    }

  /* Store the session description structure */
  priv->home = su_home_create ();
  priv->remote_sdp = sdp_session_dup (priv->home, sdp);
  g_return_val_if_fail (priv->remote_sdp != NULL, FALSE);

  authoritative = (priv->state == TPSIP_MEDIA_SESSION_STATE_INVITE_RECEIVED
                || priv->state == TPSIP_MEDIA_SESSION_STATE_REINVITE_RECEIVED);
  if (!priv_update_remote_media (session, authoritative))
    return FALSE;

finally:
  /* Make sure to always transition states and send out the response,
   * even if no stream-engine roundtrips were initiated */
  priv_request_response_step (session);
  return TRUE;
}

void
priv_add_stream_list_entry (GPtrArray *list,
                            TpsipMediaStream *stream,
                            TpsipMediaSession *session)
{
  TpsipMediaSessionPrivate *priv = TPSIP_MEDIA_SESSION_GET_PRIVATE (session);
  GValue entry = { 0 };
  GType stream_type;
  guint id;
  TpMediaStreamType type = TP_MEDIA_STREAM_TYPE_AUDIO;
  TpMediaStreamState connection_state = TP_MEDIA_STREAM_STATE_CONNECTED;
  TpMediaStreamDirection direction = TP_MEDIA_STREAM_DIRECTION_BIDIRECTIONAL;
  guint pending_send_flags = 0;

  g_assert(stream != NULL);

  g_object_get (stream,
                "id", &id,
                "media-type", &type,
                "state", &connection_state,
                "direction", &direction,
                "pending-send-flags", &pending_send_flags,
                NULL);

  stream_type = TP_STRUCT_TYPE_MEDIA_STREAM_INFO;

  g_value_init (&entry, stream_type);
  g_value_take_boxed (&entry,
                      dbus_g_type_specialized_construct (stream_type));

  dbus_g_type_struct_set (&entry,
                          0, id,
                          1, priv->peer,
                          2, type,
                          3, connection_state,
                          4, direction,
                          5, pending_send_flags,
                          G_MAXUINT);

  g_ptr_array_add (list, g_value_get_boxed (&entry));
}

gboolean tpsip_media_session_request_streams (TpsipMediaSession *session,
					    const GArray *media_types,
					    GPtrArray *ret,
					    GError **error)
{
  guint i;

  DEBUG ("enter");

  /* Validate the media types before creating any streams */
  for (i = 0; i < media_types->len; i++) {
    guint media_type = g_array_index (media_types, guint, i);
    if (!tpsip_media_session_supports_media_type (media_type))
      {
        g_set_error (error, TP_ERRORS, TP_ERROR_NOT_AVAILABLE,
                     "media type #%u is not supported", i);
        return FALSE;
      }
  }

  for (i = 0; i < media_types->len; i++) {
    guint media_type = g_array_index (media_types, guint, i);
    TpsipMediaStream *stream;

    stream = tpsip_media_session_add_stream (session,
        media_type,
        TP_MEDIA_STREAM_DIRECTION_BIDIRECTIONAL,
        TRUE);

    if (stream == NULL)
      {
        g_set_error (error, TP_ERRORS, TP_ERROR_NOT_AVAILABLE,
                     "creation of stream %u failed", i);
        /* XXX: should we close the streams already created as part of
         * this request, despite having emitted signals about them? */
        return FALSE;
      }

    priv_add_stream_list_entry (ret, stream, session);
  }

  priv_local_media_changed (session);

  return TRUE;
}

gboolean
tpsip_media_session_remove_streams (TpsipMediaSession *self,
                                  const GArray *stream_ids,
                                  GError **error)
{
  TpsipMediaStream *stream;
  guint stream_id;
  guint i;

  DEBUG ("enter");

  for (i = 0; i < stream_ids->len; i++)
    {
      stream_id = g_array_index (stream_ids, guint, i);
      stream = tpsip_media_session_get_stream (self, stream_id, error);
      if (stream == NULL)
        return FALSE;
      tpsip_media_stream_close (stream);
    }

  priv_local_media_changed (self);

  return TRUE;
}

void tpsip_media_session_list_streams (TpsipMediaSession *session,
                                     GPtrArray *ret)
{
  TpsipMediaSessionPrivate *priv = TPSIP_MEDIA_SESSION_GET_PRIVATE (session);
  TpsipMediaStream *stream;
  guint i;

  for (i = 0; i < priv->streams->len; i++)
    {
      stream = g_ptr_array_index(priv->streams, i);
      if (stream)
        priv_add_stream_list_entry (ret, stream, session);
    }
}

gboolean
tpsip_media_session_request_stream_direction (TpsipMediaSession *self,
                                              guint stream_id,
                                              guint direction,
                                              GError **error)
{
  TpsipMediaSessionPrivate *priv = TPSIP_MEDIA_SESSION_GET_PRIVATE (self);
  TpsipMediaStream *stream;

  stream = tpsip_media_session_get_stream (self, stream_id, error);
  if (stream == NULL)
    {
      g_set_error (error, TP_ERRORS, TP_ERROR_INVALID_ARGUMENT,
                   "stream %u does not exist", stream_id);
      return FALSE;
    }

  SESSION_DEBUG (self, "direction %u requested for stream %u",
      direction, stream_id);

  if (priv->state == TPSIP_MEDIA_SESSION_STATE_INVITE_RECEIVED
      || priv->state == TPSIP_MEDIA_SESSION_STATE_REINVITE_RECEIVED)
    {
      /* While processing a session offer, we can only mask out direction
       * requested by the remote peer */
      direction &= tpsip_media_stream_get_requested_direction (stream);
    }

  tpsip_media_stream_set_direction (stream,
                                    direction,
                                    TP_MEDIA_STREAM_PENDING_REMOTE_SEND);

  return TRUE;
}

static void
priv_save_event (TpsipMediaSession *self)
{
  TpsipMediaSessionPrivate *priv = TPSIP_MEDIA_SESSION_GET_PRIVATE (self);
  TpsipConnection *conn = NULL;

  priv_zap_event (self);

  g_object_get (priv->channel, "connection", &conn, NULL);

  g_return_if_fail (conn != NULL);

  tpsip_conn_save_event (conn, priv->saved_event);

  g_object_unref (conn);

#ifdef ENABLE_DEBUG
  {
    nua_event_data_t const *ev_data = nua_event_data (priv->saved_event);
    g_assert (ev_data != NULL);
    DEBUG("saved the last event: %s %hd %s", nua_event_name (ev_data->e_event), ev_data->e_status, ev_data->e_phrase);
  }
#endif
}

static void
priv_zap_event (TpsipMediaSession *self)
{
  TpsipMediaSessionPrivate *priv = TPSIP_MEDIA_SESSION_GET_PRIVATE (self);

  if (priv->saved_event[0])
    {
      nua_event_data_t const *ev_data = nua_event_data (priv->saved_event);
      g_assert (ev_data != NULL);
      WARNING ("zapping unhandled saved event '%s'", nua_event_name (ev_data->e_event));
      nua_destroy_event (priv->saved_event);
    }
}

void
tpsip_media_session_receive_invite (TpsipMediaSession *self)
{
  TpsipMediaSessionPrivate *priv = TPSIP_MEDIA_SESSION_GET_PRIVATE (self);

  g_return_if_fail (priv->state == TPSIP_MEDIA_SESSION_STATE_CREATED);  
  g_return_if_fail (priv->nua_op != NULL);

  priv->remote_initiated = TRUE;

  nua_respond (priv->nua_op, SIP_180_RINGING, TAG_END());

  tpsip_media_session_change_state (self, TPSIP_MEDIA_SESSION_STATE_INVITE_RECEIVED);
}

void
tpsip_media_session_receive_reinvite (TpsipMediaSession *self)
{
  TpsipMediaSessionPrivate *priv = TPSIP_MEDIA_SESSION_GET_PRIVATE (self);

  /* Check for permitted state transitions */
  switch (priv->state)
    {
    case TPSIP_MEDIA_SESSION_STATE_ACTIVE:
    case TPSIP_MEDIA_SESSION_STATE_RESPONSE_RECEIVED:
      break;
    case TPSIP_MEDIA_SESSION_STATE_REINVITE_PENDING:
      g_source_remove (priv->glare_timer_id);
      break;
    default:
      g_return_if_reached ();
    }

  priv_save_event (self);

  tpsip_media_session_change_state (self, TPSIP_MEDIA_SESSION_STATE_REINVITE_RECEIVED);
}

void
tpsip_media_session_accept (TpsipMediaSession *self)
{
  TpsipMediaSessionPrivate *priv = TPSIP_MEDIA_SESSION_GET_PRIVATE (self);

  if (priv->accepted)
    return;

  SESSION_DEBUG (self, "accepting the session");

  priv->accepted = TRUE;

  /* Apply the pending send flags */
  priv_apply_streams_pending_direction (self,
      TP_MEDIA_STREAM_PENDING_LOCAL_SEND |
      TP_MEDIA_STREAM_PENDING_REMOTE_SEND);

  /* Will change session state to active when streams are ready */
  priv_request_response_step (self);
}

void
tpsip_media_session_respond (TpsipMediaSession *self,
                             gint status,
                             const char *message)
{
  TpsipMediaSessionPrivate *priv = TPSIP_MEDIA_SESSION_GET_PRIVATE (self);

  SESSION_DEBUG (self, "responding: %03d %s", status, message ? message : "");

  if (message != NULL && !message[0])
    message = NULL;

  if (priv->nua_op)
    nua_respond (priv->nua_op, status, message, TAG_END());
}

gboolean tpsip_media_session_is_accepted (TpsipMediaSession *self)
{
  TpsipMediaSessionPrivate *priv = TPSIP_MEDIA_SESSION_GET_PRIVATE (self);
  return priv->accepted;
}

static gboolean
priv_glare_retry (gpointer session)
{
  TpsipMediaSession *self = session;
  TpsipMediaSessionPrivate *priv = TPSIP_MEDIA_SESSION_GET_PRIVATE (self);

  SESSION_DEBUG (self, "glare resolution interval is over");

  if (priv->state == TPSIP_MEDIA_SESSION_STATE_REINVITE_PENDING)
    priv_session_invite (self, TRUE);

  /* Reap the timer */
  priv->glare_timer_id = 0;
  return FALSE;
}

void
tpsip_media_session_resolve_glare (TpsipMediaSession *self)
{
  TpsipMediaSessionPrivate *priv = TPSIP_MEDIA_SESSION_GET_PRIVATE (self);
  guint interval;

  if (priv->state != TPSIP_MEDIA_SESSION_STATE_REINVITE_SENT)
    {
      SESSION_DEBUG (self, "glare resolution triggered in unexpected state");
      return;
    }

  /*
   * Set the grace interval accordinlgly to RFC 3261 section 14.1:
   *
   *  1. If the UAC is the owner of the Call-ID of the dialog ID
   *     (meaning it generated the value), T has a randomly chosen value
   *     between 2.1 and 4 seconds in units of 10 ms.
   *  2. If the UAC is not the owner of the Call-ID of the dialog ID, T
   *     has a randomly chosen value of between 0 and 2 seconds in units
   *     of 10 ms.
   */
  if (priv->pending_offer)
    interval = 0;       /* cut short, we have new things to negotiate */
  else if (priv->remote_initiated)
    interval = g_random_int_range (0, 200) * 10;
  else
    interval = g_random_int_range (210, 400) * 10;

  if (priv->glare_timer_id != 0)
    g_source_remove (priv->glare_timer_id);

  priv->glare_timer_id = g_timeout_add (interval, priv_glare_retry, self);

  SESSION_DEBUG (self, "glare resolution interval %u msec", interval);

  tpsip_media_session_change_state (
        self, TPSIP_MEDIA_SESSION_STATE_REINVITE_PENDING);
}

static TpsipMediaStream *
tpsip_media_session_get_stream (TpsipMediaSession *self,
                                guint stream_id,
                                GError **error)
{
  TpsipMediaSessionPrivate *priv = TPSIP_MEDIA_SESSION_GET_PRIVATE (self);
  TpsipMediaStream *stream;

  g_assert (priv->streams != NULL);

  if (stream_id >= priv->streams->len)
    {
      g_set_error (error, TP_ERRORS, TP_ERROR_INVALID_ARGUMENT,
                   "stream ID %u is invalid", stream_id);
      return NULL;
    }

  stream = g_ptr_array_index (priv->streams, stream_id);

  if (stream == NULL)
    {
      g_set_error (error, TP_ERRORS, TP_ERROR_INVALID_ARGUMENT,
                   "stream %u does not exist", stream_id);
      return NULL;
    }

  return stream;
}

TpLocalHoldState
tpsip_media_session_get_hold_state (TpsipMediaSession *self)
{
  TpsipMediaSessionPrivate *priv = TPSIP_MEDIA_SESSION_GET_PRIVATE (self);
  return priv->hold_state;
}

static gboolean
tpsip_media_session_is_local_hold_ongoing (TpsipMediaSession *self)
{
  TpsipMediaSessionPrivate *priv = TPSIP_MEDIA_SESSION_GET_PRIVATE (self);
  return (priv->hold_state == TP_LOCAL_HOLD_STATE_HELD
          || priv->hold_state == TP_LOCAL_HOLD_STATE_PENDING_HOLD);
}

static void
priv_initiate_hold (TpsipMediaSession *self,
                    gboolean hold,
                    TpLocalHoldStateReason reason)
{
  TpsipMediaSessionPrivate *priv = TPSIP_MEDIA_SESSION_GET_PRIVATE (self);
  gboolean stream_hold_requested = FALSE;
  TpsipMediaStream *stream;
  guint i;

  DEBUG("enter");

  if (hold)
    {
      if (priv->hold_state == TP_LOCAL_HOLD_STATE_HELD
          || priv->hold_state == TP_LOCAL_HOLD_STATE_PENDING_HOLD)
        {
          MESSAGE ("redundant hold request");
          return;
        }
    }
  else
    {
      if (priv->hold_state == TP_LOCAL_HOLD_STATE_UNHELD
          || priv->hold_state == TP_LOCAL_HOLD_STATE_PENDING_UNHOLD)
        {
          MESSAGE ("redundant unhold request");
          return;
        }
    }

  /* Emit the hold notification for every stream that needs it */
  for (i = 0; i < priv->streams->len; i++)
    {
      stream = g_ptr_array_index(priv->streams, i);
      if (stream != NULL
          && tpsip_media_stream_request_hold_state (stream, hold))
        stream_hold_requested = TRUE;
    }

  if (stream_hold_requested)
    {
      priv->hold_state = hold? TP_LOCAL_HOLD_STATE_PENDING_HOLD
                             : TP_LOCAL_HOLD_STATE_PENDING_UNHOLD;
    }
  else
    {
      /* There were no streams to flip, short cut to the final state */
      priv->hold_state = hold? TP_LOCAL_HOLD_STATE_HELD
                             : TP_LOCAL_HOLD_STATE_UNHELD;
    }
  priv->hold_reason = reason;

  tp_svc_channel_interface_hold_emit_hold_state_changed (priv->channel,
      priv->hold_state, reason);
}

static void
priv_finalize_hold (TpsipMediaSession *self)
{
  TpsipMediaSessionPrivate *priv = TPSIP_MEDIA_SESSION_GET_PRIVATE (self);
  TpsipMediaStream *stream;
  TpLocalHoldState final_hold_state;
  guint hold_mask;
  guint unhold_mask;
  guint i;
  gboolean held = FALSE;

  DEBUG("enter");

  switch (priv->hold_state)
    {
    case TP_LOCAL_HOLD_STATE_PENDING_HOLD:
      held = TRUE;
      break;
    case TP_LOCAL_HOLD_STATE_PENDING_UNHOLD:
      held = FALSE;
      break;
    default:
      /* Streams changed state without request, signal this to the client.
       * All streams should have the same hold state at this point,
       * so just query one of them for the current hold state */
      stream = NULL;
      for (i = 0; i < priv->streams->len; i++)
        {
          stream = g_ptr_array_index(priv->streams, i);
          if (stream != NULL)
            break;
        }
      g_return_if_fail (stream != NULL);

      g_object_get (stream, "hold-state", &held, NULL);
    }

  if (held)
    {
      final_hold_state = TP_LOCAL_HOLD_STATE_HELD;
      hold_mask = TP_MEDIA_STREAM_DIRECTION_SEND;
      unhold_mask = 0;
    }
  else
    {
      final_hold_state = TP_LOCAL_HOLD_STATE_UNHELD;
      hold_mask = TP_MEDIA_STREAM_DIRECTION_BIDIRECTIONAL;
      unhold_mask = TP_MEDIA_STREAM_DIRECTION_RECEIVE;
    }

  priv->hold_state = final_hold_state;
  tp_svc_channel_interface_hold_emit_hold_state_changed (priv->channel,
      final_hold_state, priv->hold_reason);

  /* Set stream directions accordingly to the achieved hold state */
  for (i = 0; i < priv->streams->len; i++)
    {
      stream = g_ptr_array_index(priv->streams, i);
      if (stream != NULL)
        {
          guint direction = tpsip_media_stream_get_requested_direction (stream);
          direction &= hold_mask;
          direction |= unhold_mask;
          tpsip_media_stream_set_direction (stream,
              direction,
              TP_MEDIA_STREAM_PENDING_REMOTE_SEND
                  | TP_MEDIA_STREAM_PENDING_LOCAL_SEND);
        }
    }
}

void
tpsip_media_session_request_hold (TpsipMediaSession *self,
                                  gboolean hold)
{
  priv_initiate_hold (self,
                      hold,
                      TP_LOCAL_HOLD_STATE_REASON_REQUESTED);
}

gboolean
tpsip_media_session_start_telephony_event (TpsipMediaSession *self,
                                         guint stream_id,
                                         guchar event,
                                         GError **error)
{
  TpsipMediaStream *stream;

  stream = tpsip_media_session_get_stream (self, stream_id, error);
  if (stream == NULL)
    return FALSE;

  if (tpsip_media_stream_get_media_type (stream) != TP_MEDIA_STREAM_TYPE_AUDIO)
    {
      g_set_error (error, TP_ERRORS, TP_ERROR_NOT_AVAILABLE,
                   "non-audio stream %u does not support telephony events", stream_id);
      return FALSE;
    }

  DEBUG("starting telephony event %u on stream %u", (guint) event, stream_id);

  tpsip_media_stream_start_telephony_event (stream, event);

  return TRUE;
}

gboolean
tpsip_media_session_stop_telephony_event  (TpsipMediaSession *self,
                                         guint stream_id,
                                         GError **error)
{
  TpsipMediaStream *stream;

  stream = tpsip_media_session_get_stream (self, stream_id, error);
  if (stream == NULL)
    return FALSE;

  if (tpsip_media_stream_get_media_type (stream) != TP_MEDIA_STREAM_TYPE_AUDIO)
    {
      g_set_error (error, TP_ERRORS, TP_ERROR_NOT_AVAILABLE,
                   "non-audio stream %u does not support telephony events; spurious use of the stop event?", stream_id);
      return FALSE;
    }

  DEBUG("stopping the telephony event on stream %u", stream_id);

  tpsip_media_stream_stop_telephony_event (stream);

  return TRUE;
}

gint
tpsip_media_session_rate_native_transport (TpsipMediaSession *session,
                                         const GValue *transport)
{
  TpsipMediaSessionPrivate *priv = TPSIP_MEDIA_SESSION_GET_PRIVATE (session);
  gint result = 0;
  gchar *address = NULL;
  guint proto = TP_MEDIA_STREAM_BASE_PROTO_UDP;

  dbus_g_type_struct_get (transport,
                          1, &address,
                          3, &proto,
                          G_MAXUINT);

  g_assert (address != NULL);

  if (proto != TP_MEDIA_STREAM_BASE_PROTO_UDP)
    result = -1;
  /* XXX: this will not work properly when IPv6 support comes */
  else if (priv->local_ip_address != NULL
      && strcmp (address, priv->local_ip_address) == 0)
    result = 1;

  g_free (address);

  return result;
}

static void
priv_session_set_streams_playing (TpsipMediaSession *session, gboolean playing)
{
  TpsipMediaSessionPrivate *priv = TPSIP_MEDIA_SESSION_GET_PRIVATE (session);
  TpsipMediaStream *stream;
  guint i;

  for (i = 0; i < priv->streams->len; i++)
    {
      stream = g_ptr_array_index(priv->streams, i);
      if (stream != NULL)
        tpsip_media_stream_set_playing (stream, playing);
    }
}

static void
priv_local_media_changed (TpsipMediaSession *session)
{
  TpsipMediaSessionPrivate *priv = TPSIP_MEDIA_SESSION_GET_PRIVATE (session);

  switch (priv->state)
    {
    case TPSIP_MEDIA_SESSION_STATE_CREATED:
      /* If all streams are ready, send an offer now */
      priv_request_response_step (session);
      break;
    case TPSIP_MEDIA_SESSION_STATE_INVITE_RECEIVED:
    case TPSIP_MEDIA_SESSION_STATE_REINVITE_RECEIVED:
      /* The changes to existing streams will be included in the
       * eventual answer (FIXME: implement postponed direction changes,
       * which are applied after the remote offer has been processed).
       * Check, however, if there are new streams not present in the
       * remote offer, that will need another offer-answer round */
      if (priv->remote_stream_count < priv->streams->len)
        priv->pending_offer = TRUE;
      break;
    case TPSIP_MEDIA_SESSION_STATE_INVITE_SENT:
    case TPSIP_MEDIA_SESSION_STATE_REINVITE_SENT:
    case TPSIP_MEDIA_SESSION_STATE_RESPONSE_RECEIVED:
      /* Cannot send another offer right now */
      priv->pending_offer = TRUE;
      break;
    case TPSIP_MEDIA_SESSION_STATE_ACTIVE:
      /* Check if we are allowed to send re-INVITES */
      {
        gboolean immutable_streams = FALSE;
        g_object_get (priv->channel,
            "immutable-streams", &immutable_streams,
            NULL);
        if (immutable_streams) {
          g_message ("sending of a local media update disabled by parameter 'immutable-streams'");
          break;
        }
      }
      /* Fall through to the next case */
    case TPSIP_MEDIA_SESSION_STATE_REINVITE_PENDING:
      if (priv->local_non_ready == 0)
        priv_session_invite (session, TRUE);
      else
        priv->pending_offer = TRUE;
      break;
    default:
      g_assert_not_reached();
    }
}

static void
priv_update_remote_hold (TpsipMediaSession *session)
{
  TpsipMediaSessionPrivate *priv = TPSIP_MEDIA_SESSION_GET_PRIVATE (session);
  TpsipMediaStream *stream;
  gboolean has_streams = FALSE;
  gboolean remote_held = TRUE;
  guint direction;
  guint i;

  /* The call is remotely unheld if there's at least one sending stream */
  for (i = 0; i < priv->streams->len; i++)
    {
      stream = g_ptr_array_index(priv->streams, i);
      if (stream != NULL)
        {
          direction = tpsip_media_stream_get_requested_direction (stream);

          if ((direction & TP_MEDIA_STREAM_DIRECTION_SEND) != 0)
            remote_held = FALSE;

          has_streams = TRUE;
        }
    }

  if (!has_streams)
    return;

  DEBUG("the session is remotely %s", remote_held? "held" : "unheld");

  if (remote_held)
    tpsip_media_channel_change_call_state (priv->channel,
                                           priv->peer,
                                           TP_CHANNEL_CALL_STATE_HELD,
                                           0);
  else
    tpsip_media_channel_change_call_state (priv->channel,
                                           priv->peer,
                                           0,
                                           TP_CHANNEL_CALL_STATE_HELD);
}

gchar *
tpsip_sdp_get_string_attribute (const sdp_attribute_t *attrs, const char *name)
{
  sdp_attribute_t *attr;

  attr = sdp_attribute_find (attrs, name);
  if (attr == NULL)
    return NULL;

  return g_strdup (attr->a_value);
}

static gboolean
priv_update_remote_media (TpsipMediaSession *session, gboolean authoritative)
{
  TpsipMediaSessionPrivate *priv = TPSIP_MEDIA_SESSION_GET_PRIVATE (session);
  const sdp_session_t *sdp = priv->remote_sdp;
  const sdp_media_t *media;
  gboolean has_supported_media = FALSE;
  guint direction_up_mask;
  guint pending_send_mask;
  guint i;

  g_return_val_if_fail (sdp != NULL, FALSE);

  /* Update the session-wide parameters
   * before updating streams' media */

  priv->remote_ptime     = tpsip_sdp_get_string_attribute (
      sdp->sdp_attributes, "ptime");
  priv->remote_max_ptime = tpsip_sdp_get_string_attribute (
      sdp->sdp_attributes, "maxptime");

  priv->rtcp_enabled = !tpsip_sdp_rtcp_bandwidth_throttled (
                                sdp->sdp_bandwidths);

  /*
   * Do not allow:
   * 1) an answer to bump up directions beyond what's been offered;
   * 2) an offer to remove the local hold.
   */
  if (authoritative)
    direction_up_mask
        = tpsip_media_session_is_local_hold_ongoing (session)
                ? TP_MEDIA_STREAM_DIRECTION_SEND
                : TP_MEDIA_STREAM_DIRECTION_BIDIRECTIONAL;
  else
    direction_up_mask = 0;

  /* A remote media requesting to enable sending would need local approval.
   * Also, if there have been any local media updates pending a re-INVITE,
   * keep or bump the pending remote send flag on the streams: it will
   * be resolved in the next re-INVITE transaction */
  pending_send_mask = TP_MEDIA_STREAM_PENDING_LOCAL_SEND;
  if (priv->pending_offer)
    pending_send_mask |= TP_MEDIA_STREAM_PENDING_REMOTE_SEND;

  media = sdp->sdp_media;

  /* note: for each session, we maintain an ordered list of
   *       streams (SDP m-lines) which are matched 1:1 to
   *       the streams of the remote SDP */

  for (i = 0; media != NULL; media = media->m_next, i++)
    {
      TpsipMediaStream *stream = NULL;
      guint media_type;

      media_type = tpsip_tp_media_type (media->m_type);

      if (i >= priv->streams->len)
        stream = tpsip_media_session_add_stream (
                        session,
                        media_type,
                        tpsip_media_stream_direction_from_remote_media (media),
                        FALSE);
      else
        stream = g_ptr_array_index(priv->streams, i);

      /* note: it is ok for the stream to be NULL (unsupported media type) */
      if (stream == NULL)
        continue;

      DEBUG("setting remote SDP for stream %u", i);

      if (media->m_rejected)
        {
          DEBUG("the stream has been rejected, closing");
        }
      else if (tpsip_media_stream_get_media_type (stream) != media_type)
        {
          /* XXX: close this stream and create a new one in its place? */
          WARNING ("The peer has changed the media type, don't know what to do");
        }
      else if (tpsip_media_stream_set_remote_media (stream,
                                                    media,
                                                    direction_up_mask,
                                                    pending_send_mask))
        {
          has_supported_media = TRUE;
          continue;
        }

      /* There have been problems with the stream update, kill the stream */
      tpsip_media_stream_close (stream);
    }
  g_assert(media == NULL);
  g_assert(i <= priv->streams->len);
  g_assert(!authoritative || i == priv->remote_stream_count);

  if (i < priv->streams->len && !priv->pending_offer)
    {
      /*
       * It's not defined what we should do if there are previously offered
       * streams not accounted in the remote SDP, in violation of RFC 3264.
       * Closing them off serves resource preservation and gives better
       * clue to the client as to the real state of the session.
       * Note that this situation is masked if any local media updates
       * have been requested and are pending until the present remote session
       * answer is received and applied. In such a case, we'll issue a new offer
       * at the closest available time, with the "overhanging" stream entries
       * intact.
       */
      do
        {
          TpsipMediaStream *stream;
          stream = g_ptr_array_index(priv->streams, i);
          if (stream != NULL)
            {
              MESSAGE ("closing a mismatched stream %u", i);
              tpsip_media_stream_close (stream);
            }
        }
      while (++i < priv->streams->len);
    }

  if (has_supported_media)
    priv_update_remote_hold (session);

  DEBUG("exit");

  return has_supported_media;
}

static void
priv_session_rollback (TpsipMediaSession *session)
{
  TpsipMediaSessionPrivate *priv = TPSIP_MEDIA_SESSION_GET_PRIVATE (session);

  DEBUG("enter");

  if (priv->remote_sdp != NULL)
    {
      priv->remote_sdp = NULL;
      g_assert (priv->home != NULL);
      su_home_unref (priv->home);
      priv->home = NULL;
    }
  if (priv->backup_remote_sdp == NULL)
    {
      tpsip_media_session_terminate (session);
      return;
    }

  /* restore remote SDP from the backup */
  priv->remote_sdp = priv->backup_remote_sdp;
  g_assert (priv->backup_home != NULL);
  priv->home = priv->backup_home;
  priv->backup_remote_sdp = NULL;
  priv->backup_home = NULL;

  priv_update_remote_media (session, FALSE);

  if (priv->saved_event[0])
    {
      nua_respond (priv->nua_op, SIP_488_NOT_ACCEPTABLE,
                   NUTAG_WITH(nua_saved_event_request (priv->saved_event)),
                   TAG_END());
      nua_destroy_event (priv->saved_event);
    }
  else
    {
      nua_respond (priv->nua_op, SIP_488_NOT_ACCEPTABLE,
                   TAG_END());
    }

  tpsip_media_session_change_state (session, TPSIP_MEDIA_SESSION_STATE_ACTIVE);
}

static gboolean
priv_session_local_sdp (TpsipMediaSession *session,
                        GString *user_sdp,
                        gboolean authoritative)
{
  TpsipMediaSessionPrivate *priv = TPSIP_MEDIA_SESSION_GET_PRIVATE (session);
  gboolean has_supported_media = FALSE;
  guint len;
  guint i;

  g_return_val_if_fail (priv->local_non_ready == 0, FALSE);

  len = priv->streams->len;
  if (!authoritative && len > priv->remote_stream_count)
    {
      len = priv->remote_stream_count;
      DEBUG("clamped response to %u streams seen in the offer", len);
    }

  g_string_append (user_sdp, "v=0\r\n");

  for (i = 0; i < len; i++)
    {
      TpsipMediaStream *stream = g_ptr_array_index (priv->streams, i);
      if (stream)
        {
          user_sdp = g_string_append (user_sdp,
                                      tpsip_media_stream_local_sdp (stream));
          has_supported_media = TRUE;
        }
      else
        { 
          user_sdp = g_string_append (user_sdp, "m=audio 0 RTP/AVP 0\r\n");
        }
    }

  return has_supported_media;
}

static void
priv_session_invite (TpsipMediaSession *session, gboolean reinvite)
{
  TpsipMediaSessionPrivate *priv = TPSIP_MEDIA_SESSION_GET_PRIVATE (session);
  GString *user_sdp;

  DEBUG("enter");

  g_return_if_fail (priv->nua_op != NULL);

  user_sdp = g_string_new (NULL);

  if (priv_session_local_sdp (session, user_sdp, TRUE))
    {
      /* We need to be prepared to receive media right after the
       * offer is sent, so we must set the streams to playing */
      priv_session_set_streams_playing (session, TRUE);

      nua_invite (priv->nua_op,
                  SOATAG_USER_SDP_STR(user_sdp->str),
                  SOATAG_RTP_SORT(SOA_RTP_SORT_REMOTE),
                  SOATAG_RTP_SELECT(SOA_RTP_SELECT_ALL),
                  NUTAG_AUTOANSWER(0),
                  TAG_IF(reinvite,
                         NUTAG_INVITE_TIMER (TPSIP_REINVITE_TIMEOUT)),
                  TAG_END());
      priv->pending_offer = FALSE;

      tpsip_media_session_change_state (
                session,
                reinvite? TPSIP_MEDIA_SESSION_STATE_REINVITE_SENT
                        : TPSIP_MEDIA_SESSION_STATE_INVITE_SENT);
    }
  else
    WARNING ("cannot send a valid SDP offer, are there no streams?");

  g_string_free (user_sdp, TRUE);
}

static void
priv_session_respond (TpsipMediaSession *session)
{
  TpsipMediaSessionPrivate *priv = TPSIP_MEDIA_SESSION_GET_PRIVATE (session);
  GString *user_sdp;

  g_return_if_fail (priv->nua_op != NULL);

  user_sdp = g_string_new (NULL);

  if (priv_session_local_sdp (session, user_sdp, FALSE))
    {
      msg_t *msg;

      /* We need to be prepared to receive media right after the
       * answer is sent, so we must set the streams to playing */
      priv_session_set_streams_playing (session, TRUE);

      msg = (priv->saved_event[0])
                ? nua_saved_event_request (priv->saved_event) : NULL;

      nua_respond (priv->nua_op, SIP_200_OK,
                   TAG_IF(msg, NUTAG_WITH(msg)),
                   SOATAG_USER_SDP_STR (user_sdp->str),
                   SOATAG_RTP_SORT(SOA_RTP_SORT_REMOTE),
                   SOATAG_RTP_SELECT(SOA_RTP_SELECT_ALL),
                   NUTAG_AUTOANSWER(0),
                   TAG_END());

      if (priv->saved_event[0])
        nua_destroy_event (priv->saved_event);

      tpsip_media_session_change_state (session, TPSIP_MEDIA_SESSION_STATE_ACTIVE);
    }
  else
    {
      WARNING ("cannot respond with a valid SDP answer, were all streams closed?");

      priv_session_rollback (session);
    }

  g_string_free (user_sdp, TRUE);
}

static gboolean
priv_is_codec_intersect_pending (TpsipMediaSession *session)
{
  TpsipMediaSessionPrivate *priv = TPSIP_MEDIA_SESSION_GET_PRIVATE (session);
  guint i;

  for (i = 0; i < priv->streams->len; i++)
    {
      TpsipMediaStream *stream = g_ptr_array_index (priv->streams, i);
      if (stream != NULL
          && tpsip_media_stream_is_codec_intersect_pending (stream))
        return TRUE;
    }

  return FALSE;
}

/**
 * Sends requests and responses with an outbound offer/answer
 * if all streams of the session are prepared.
 * 
 * Following inputs are considered in decision making:
 *  - state of the session (is remote INVITE being handled)  
 *  - status of local streams (set up with stream-engine)
 *  - whether session is locally accepted
 */
static void
priv_request_response_step (TpsipMediaSession *session)
{
  TpsipMediaSessionPrivate *priv = TPSIP_MEDIA_SESSION_GET_PRIVATE (session);

  if (priv->local_non_ready != 0)
    {
      DEBUG("there are local streams not ready, postponed");
      return;
    }

  switch (priv->state)
    {
    case TPSIP_MEDIA_SESSION_STATE_CREATED:
      priv_session_invite (session, FALSE);
      break;
    case TPSIP_MEDIA_SESSION_STATE_RESPONSE_RECEIVED:
      if (priv->accepted
          && !priv_is_codec_intersect_pending (session))
        tpsip_media_session_change_state (session,
                                        TPSIP_MEDIA_SESSION_STATE_ACTIVE);
      break;
    case TPSIP_MEDIA_SESSION_STATE_INVITE_RECEIVED:
      /* TODO: if the call has not yet been accepted locally
       * and the remote endpoint supports 100rel, send them
       * an early session answer in a reliable 183 response */
      if (priv->accepted
          && !priv_is_codec_intersect_pending (session))
        priv_session_respond (session);
      break;
    case TPSIP_MEDIA_SESSION_STATE_REINVITE_RECEIVED:
      if (!priv_is_codec_intersect_pending (session))
        priv_session_respond (session);
      break;
    case TPSIP_MEDIA_SESSION_STATE_ACTIVE:
    case TPSIP_MEDIA_SESSION_STATE_REINVITE_PENDING:
      if (priv->pending_offer)
        priv_session_invite (session, TRUE);
      break;
    default:
      SESSION_DEBUG (session, "no action taken in the current state");
    }
}

static void
priv_stream_close_cb (TpsipMediaStream *stream,
                      TpsipMediaSession *session)
{
  TpsipMediaSessionPrivate *priv;
  guint id;

  DEBUG("enter");

  priv = TPSIP_MEDIA_SESSION_GET_PRIVATE (session);

  id = tpsip_media_stream_get_id (stream);
  g_return_if_fail (g_ptr_array_index(priv->streams, id) == stream);

  if (!tpsip_media_stream_is_local_ready (stream))
    {
      g_assert (priv->local_non_ready > 0);
      --priv->local_non_ready;
      DEBUG("stream wasn't ready, decrement the local non ready counter to %d", priv->local_non_ready);
    }

  g_object_unref (stream);

  g_ptr_array_index(priv->streams, id) = NULL;

  tp_svc_channel_type_streamed_media_emit_stream_removed (priv->channel, id);
}

static void priv_stream_ready_cb (TpsipMediaStream *stream,
				  TpsipMediaSession *session)
{
  TpsipMediaSessionPrivate *priv;

  DEBUG ("enter");

  priv = TPSIP_MEDIA_SESSION_GET_PRIVATE (session);

  g_assert (priv->local_non_ready > 0);
  --priv->local_non_ready;

  priv_request_response_step (session);
}

static void priv_stream_supported_codecs_cb (TpsipMediaStream *stream,
					     guint num_codecs,
					     TpsipMediaSession *session)
{
  TpsipMediaSessionPrivate *priv;

  priv = TPSIP_MEDIA_SESSION_GET_PRIVATE (session);

  g_assert (!tpsip_media_stream_is_codec_intersect_pending (stream));

  if (num_codecs == 0)
    {
      /* This remote media description got no codec intersection. */
      switch (priv->state)
        {
        case TPSIP_MEDIA_SESSION_STATE_RESPONSE_RECEIVED:
        case TPSIP_MEDIA_SESSION_STATE_INVITE_RECEIVED:
          DEBUG("no codec intersection, closing the stream");
          tpsip_media_stream_close (stream);
          break;
        case TPSIP_MEDIA_SESSION_STATE_REINVITE_RECEIVED:
          /* In this case, we have the stream negotiated already,
           * and we don't want to close it just because the remote party
           * offers a different set of codecs.
           * Roll back the whole session to the previously negotiated state. */
          priv_session_rollback (session);
          return;
        case TPSIP_MEDIA_SESSION_STATE_ACTIVE:
          /* We've most likely rolled back from
           * TPSIP_MEDIA_SESSION_STATE_REINVITE_RECEIVED,
           * but we may receive more than one empty codec intersection
           * in the session, so we ignore the rest */
          return;
        default:
          g_assert_not_reached();
        }
    }

  priv_request_response_step (session);
}

static void
priv_stream_state_changed_cb (TpsipMediaStream *stream,
                              guint state,
                              TpsipMediaChannel *channel)
{
  g_assert (TPSIP_IS_MEDIA_CHANNEL (channel));
  tp_svc_channel_type_streamed_media_emit_stream_state_changed(
        channel,
        tpsip_media_stream_get_id (stream), state);
}

static void
priv_stream_direction_changed_cb (TpsipMediaStream *stream,
                                  guint direction,
                                  guint pending_send_flags,
                                  TpsipMediaChannel *channel)
{
  g_assert (TPSIP_IS_MEDIA_CHANNEL (channel));
  tp_svc_channel_type_streamed_media_emit_stream_direction_changed (
        channel,
        tpsip_media_stream_get_id (stream), direction, pending_send_flags);
}

static void
priv_stream_hold_state_cb (TpsipMediaStream *stream,
                           GParamSpec *pspec,
                           TpsipMediaSession *session)
{
  TpsipMediaSessionPrivate *priv = TPSIP_MEDIA_SESSION_GET_PRIVATE (session);
  gboolean hold;
  guint i;

  /* Determine the hold state all streams shall come to */
  switch (priv->hold_state)
    {
    case TP_LOCAL_HOLD_STATE_PENDING_HOLD:
      hold = TRUE;
      break;
    case TP_LOCAL_HOLD_STATE_PENDING_UNHOLD:
      hold = FALSE;
      break;
    default:
      MESSAGE ("unexpected hold state change from a stream");

      /* Try to follow the changes and report the resulting hold state */
      g_object_get (stream, "hold-state", &hold, NULL);
      priv->hold_reason = TP_LOCAL_HOLD_STATE_REASON_NONE;
    }

  /* Check if all streams have reached the desired hold state */
  for (i = 0; i < priv->streams->len; i++)
    {
      stream = g_ptr_array_index (priv->streams, i);
      if (stream != NULL)
        {
          gboolean stream_held = FALSE;
          g_object_get (stream, "hold-state", &stream_held, NULL);
          if ((!stream_held) != (!hold))
            {
              DEBUG("hold/unhold not complete yet");
              return;
            }
        }
    }

  priv_finalize_hold (session);
}

static void
priv_stream_unhold_failure_cb (TpsipMediaStream *stream,
                               TpsipMediaSession *session)
{
  priv_initiate_hold (session,
                      TRUE,
                      TP_LOCAL_HOLD_STATE_REASON_RESOURCE_NOT_AVAILABLE);
}

TpsipMediaStream*
tpsip_media_session_add_stream (TpsipMediaSession *self,
                                guint media_type,
                                TpMediaStreamDirection direction,
                                gboolean created_locally)
{
  TpsipMediaSessionPrivate *priv = TPSIP_MEDIA_SESSION_GET_PRIVATE (self);
  TpsipMediaStream *stream = NULL;

  DEBUG ("enter");

  if (tpsip_media_session_supports_media_type (media_type)) {
    guint stream_id;
    gchar *object_path;
    guint pending_send_flags;

    stream_id = priv->streams->len;
    object_path = g_strdup_printf ("%s/MediaStream%u",
                                   priv->object_path,
                                   stream_id);
    pending_send_flags = created_locally
        ? TP_MEDIA_STREAM_PENDING_REMOTE_SEND
        : TP_MEDIA_STREAM_PENDING_LOCAL_SEND;

    if (!created_locally)
      direction &= ~TP_MEDIA_STREAM_DIRECTION_SEND;

    if (tpsip_media_session_is_local_hold_ongoing (self))
      direction &= ~TP_MEDIA_STREAM_DIRECTION_RECEIVE;

    stream = g_object_new (TPSIP_TYPE_MEDIA_STREAM,
                           "dbus-daemon", priv->dbus_daemon,
			   "media-session", self,
			   "media-type", media_type,
			   "object-path", object_path,
			   "id", stream_id,
                           "direction", direction,
                           "pending-send-flags", pending_send_flags,
                           "created-locally", created_locally,
			   NULL);

    g_free (object_path);
 
    g_signal_connect (stream, "close",
                      G_CALLBACK (priv_stream_close_cb),
                      self);
    g_signal_connect (stream, "ready",
		      G_CALLBACK (priv_stream_ready_cb),
		      self);
    g_signal_connect (stream, "supported-codecs",
		      G_CALLBACK (priv_stream_supported_codecs_cb),
		      self);
    g_signal_connect (stream, "state-changed",
                      G_CALLBACK (priv_stream_state_changed_cb),
                      priv->channel);
    g_signal_connect (stream, "direction-changed",
                      G_CALLBACK (priv_stream_direction_changed_cb),
                      priv->channel);
    g_signal_connect_swapped (stream, "local-media-updated",
                              G_CALLBACK (priv_local_media_changed),
                              self);
    g_signal_connect (stream, "notify::hold-state",
                      G_CALLBACK (priv_stream_hold_state_cb),
                      self);
    g_signal_connect (stream, "unhold-failure",
                      G_CALLBACK (priv_stream_unhold_failure_cb),
                      self);

    g_assert (priv->local_non_ready >= 0);
    ++priv->local_non_ready;

    if (priv->se_ready)
      priv_emit_new_stream (self, stream);

    tp_svc_channel_type_streamed_media_emit_stream_added (priv->channel,
                                                          stream_id,
                                                          priv->peer,
                                                          media_type);
    if (direction != TP_MEDIA_STREAM_DIRECTION_RECEIVE
        || pending_send_flags != TP_MEDIA_STREAM_PENDING_LOCAL_SEND)
      {
        tp_svc_channel_type_streamed_media_emit_stream_direction_changed (
            priv->channel,
            stream_id,
            direction,
            pending_send_flags);
      }
  }

  /* note: we add an entry even for unsupported media types */
  g_ptr_array_add (priv->streams, stream);

  DEBUG ("exit");

  return stream;
}

static void
session_handler_iface_init (gpointer g_iface, gpointer iface_data)
{
  TpSvcMediaSessionHandlerClass *klass = (TpSvcMediaSessionHandlerClass *)g_iface;

#define IMPLEMENT(x) tp_svc_media_session_handler_implement_##x (\
    klass, (tp_svc_media_session_handler_##x##_impl) tpsip_media_session_##x)
  IMPLEMENT(error);
  IMPLEMENT(ready);
#undef IMPLEMENT
}

/* Checks if RTCP is not disabled with bandwidth modifiers
 * as described in RFC 3556 */
gboolean
tpsip_sdp_rtcp_bandwidth_throttled (const sdp_bandwidth_t *b)
{
  const sdp_bandwidth_t *b_RS = NULL;
  const sdp_bandwidth_t *b_RR = NULL;

  while (b != NULL)
    {
      if (b->b_modifier_name != NULL)
        {
          if (strcmp (b->b_modifier_name, "RS") == 0)
            b_RS = b;
          else if (strcmp (b->b_modifier_name, "RR") == 0)
            b_RR = b;
        }
      b = b->b_next;
    }

  return (b_RS != NULL && b_RS->b_value == 0
       && b_RR != NULL && b_RR->b_value == 0);
}