File: local_conference.cpp

package info (click to toggle)
linphone 5.3.105-6
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 57,048 kB
  • sloc: cpp: 166,867; ansic: 102,939; python: 8,280; java: 4,406; sh: 1,040; xml: 1,023; makefile: 777; perl: 377; objc: 190; php: 88; javascript: 38; cs: 38
file content (2241 lines) | stat: -rw-r--r-- 93,420 bytes parent folder | download | duplicates (2)
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
/*
 * Copyright (c) 2010-2023 Belledonne Communications SARL.
 *
 * This file is part of Liblinphone
 * (see https://gitlab.linphone.org/BC/public/liblinphone).
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program 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 Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */

#include <tuple>

#include "call/call-log.h"
#include "conference/params/media-session-params-p.h"
#include "conference/participant-info.h"
#include "conference/participant.h"
#include "conference/session/media-session-p.h"
#include "conference/session/mixers.h"
#include "core/core-p.h"
#include "db/main-db.h"
#include "factory/factory.h"
#include "local_conference.h"
#ifdef HAVE_ADVANCED_IM
#include "conference/handlers/local-audio-video-conference-event-handler.h"
#endif // HAVE_ADVANCED_IM

using namespace std;

LINPHONE_BEGIN_NAMESPACE

namespace MediaConference {

LocalConference::LocalConference(const shared_ptr<Core> &core,
                                 const std::shared_ptr<Address> &myAddress,
                                 CallSessionListener *listener,
                                 const std::shared_ptr<LinphonePrivate::ConferenceParams> params)
    : Conference(core, myAddress, listener, params) {

	bool_t eventLogEnabled = FALSE;
#ifdef HAVE_ADVANCED_IM
	eventLogEnabled = linphone_config_get_bool(linphone_core_get_config(getCore()->getCCore()), "misc",
	                                           "conference_event_log_enabled", TRUE);
	if (eventLogEnabled) {
		eventHandler = std::make_shared<LocalAudioVideoConferenceEventHandler>(this);
		addListener(eventHandler);
	} else {
#endif // HAVE_ADVANCED_IM
		lInfo() << "Unable to add listener to local conference as conference event package (RFC 4575) is disabled or "
		           "the SDK was not compiled with ENABLE_ADVANCED_IM flag set to on";
#ifdef HAVE_ADVANCED_IM
	}
#endif // HAVE_ADVANCED_IM

	if (!linphone_core_conference_server_enabled(core->getCCore())) {
		lWarning() << "Video capability in a conference is not supported when a device that is not a server is hosting "
		              "a conference.";
		confParams->enableVideo(false);
	}
	mMixerSession.reset(new MixerSession(*core.get()));
	mMixerSession->setSecurityLevel(confParams->getSecurityLevel());

	setState(ConferenceInterface::State::Instantiated);

	organizer = myAddress;

	// Update proxy contact address to add conference ID
	// Do not use myAddress directly as it may lack some parameter like gruu
	LinphoneAddress *cAddress = myAddress->toC();
	LinphoneAccount *account = linphone_core_lookup_known_account(core->getCCore(), cAddress);
	char *contactAddressStr = nullptr;
	if (account && Account::toCpp(account)->getOp()) {
		contactAddressStr = sal_address_as_string(Account::toCpp(account)->getOp()->getContactAddress());
	} else {
		contactAddressStr =
		    ms_strdup(linphone_core_find_best_identity(core->getCCore(), const_cast<LinphoneAddress *>(cAddress)));
	}
	std::shared_ptr<Address> contactAddress = Address::create(contactAddressStr);
	char confId[LinphonePrivate::MediaConference::LocalConference::confIdLength];
	belle_sip_random_token(confId, sizeof(confId));
	contactAddress->setUriParam("conf-id", confId);
	if (contactAddressStr) {
		ms_free(contactAddressStr);
	}

	setConferenceAddress(contactAddress);
	me->setRole(Participant::Role::Speaker);
	me->setAdmin(true);
	me->setFocus(true);

	if (!eventLogEnabled) {
		setConferenceId(ConferenceId(contactAddress, contactAddress));
	}

#ifdef HAVE_DB_STORAGE
	auto conferenceInfo = createOrGetConferenceInfo();
	auto &mainDb = getCore()->getPrivate()->mainDb;
	if (mainDb) {
		mainDb->insertConferenceInfo(conferenceInfo);
	}
#endif // HAVE_DB_STORAGE
}

LocalConference::LocalConference(const std::shared_ptr<Core> &core, SalCallOp *op)
    : Conference(core, Address::create(op->getTo()), nullptr, ConferenceParams::create(core)) {
}

LocalConference::~LocalConference() {
	if ((state != ConferenceInterface::State::Terminated) && (state != ConferenceInterface::State::Deleted)) {
		terminate();
	}
#ifdef HAVE_ADVANCED_IM
	eventHandler.reset();
#endif // HAVE_ADVANCED_IM
	mMixerSession.reset();
}

void LocalConference::createEventHandler() {
#ifdef HAVE_ADVANCED_IM
	LinphoneCore *lc = getCore()->getCCore();
	bool_t eventLogEnabled =
	    linphone_config_get_bool(linphone_core_get_config(lc), "misc", "conference_event_log_enabled", TRUE);
	if (eventLogEnabled) {
		eventHandler = std::make_shared<LocalAudioVideoConferenceEventHandler>(this);
		addListener(eventHandler);
	} else {
#endif // HAVE_ADVANCED_IM
		lInfo() << "Unable to add listener to local conference as conference event package (RFC 4575) is disabled or "
		           "the SDK was not compiled with ENABLE_ADVANCED_IM flag set to on";
#ifdef HAVE_ADVANCED_IM
	}
#endif // HAVE_ADVANCED_IM
}

void LocalConference::initWithOp(SalCallOp *op) {
	mMixerSession.reset(new MixerSession(*getCore().get()));
	setState(ConferenceInterface::State::Instantiated);
	createEventHandler();
	configure(op);
}

void LocalConference::updateConferenceInformation(SalCallOp *op) {
	auto remoteContact = op->getRemoteContactAddress();
	if (remoteContact) {
		char *salAddress = sal_address_as_string(remoteContact);
		std::shared_ptr<Address> address = Address::create(std::string(salAddress));
		if (salAddress) {
			ms_free(salAddress);
		}
		auto invited =
		    std::find_if(mInvitedParticipants.begin(), mInvitedParticipants.end(), [&address](const auto &invitee) {
			    return address->weakEqual(*invitee->getAddress());
		    }) != mInvitedParticipants.end();

		std::shared_ptr<Address> remoteAddress =
		    Address::create((op->getDir() == SalOp::Dir::Incoming) ? op->getFrom() : op->getTo());

		if (findParticipantDevice(remoteAddress, address) || invited || address->weakEqual(*organizer)) {
			lInfo() << "Updating conference informations of conference " << *getConferenceAddress();
			const auto &remoteMd = op->getRemoteMediaDescription();

			const auto times = remoteMd->times;
			time_t startTime = -1, endTime = -1;
			if (times.size() > 0) {
				std::tie(startTime, endTime) = times.front();
				confParams->setStartTime(startTime);
				confParams->setEndTime(endTime);
			}

			// The following informations are retrieved from the received INVITE:
			// - start and end time from the SDP active time attribute
			// - conference active media:
			//    - if the SDP has at least one active audio stream, audio is enabled
			//    - if the SDP has at least one active video stream, video is enabled
			// - Subject is got from the "Subject" header in the INVITE
			const auto audioEnabled = (remoteMd->nbActiveStreamsOfType(SalAudio) > 0);
			auto videoEnabled = (linphone_core_conference_server_enabled(getCore()->getCCore()))
			                        ? linphone_core_video_enabled(getCore()->getCCore())
			                        : false;
			if (!linphone_core_conference_server_enabled(getCore()->getCCore())) {
				lWarning() << "Video capability in a conference is not supported when a device that is not a server is "
				              "hosting a conference.";
			}

			bool previousVideoEnablement = confParams->videoEnabled();
			bool previousAudioEnablement = confParams->audioEnabled();

			confParams->enableAudio(audioEnabled);
			confParams->enableVideo(videoEnabled);

			if ((confParams->videoEnabled() != previousVideoEnablement) ||
			    (confParams->audioEnabled() != previousAudioEnablement)) {
				time_t creationTime = time(nullptr);
				notifyAvailableMediaChanged(creationTime, false, getMediaCapabilities());
			}
			setSubject(op->getSubject());

			confParams->enableOneParticipantConference(true);
			confParams->setStatic(true);

			auto session = const_pointer_cast<LinphonePrivate::MediaSession>(
			    static_pointer_cast<LinphonePrivate::MediaSession>(getMe()->getSession()));
			if (session) {
				auto msp = session->getPrivate()->getParams();
				msp->enableAudio(audioEnabled);
				msp->enableVideo(videoEnabled);
				msp->getPrivate()->setInConference(true);
				msp->getPrivate()->setStartTime(startTime);
				msp->getPrivate()->setEndTime(endTime);
			}

			me->setRole(Participant::Role::Speaker);
			me->setAdmin(true);
			me->setFocus(true);

			const auto resourceList = op->getContentInRemote(ContentType::ResourceLists);
			bool isEmpty = !resourceList || resourceList.value().get().isEmpty();
			fillInvitedParticipantList(op, isEmpty);

			const auto &conferenceInfo = createConferenceInfoWithCustomParticipantList(organizer, mInvitedParticipants);
			auto infoState = ConferenceInfo::State::New;
			if (isEmpty) {
				infoState = ConferenceInfo::State::Cancelled;
			} else {
				infoState = ConferenceInfo::State::Updated;
			}
			conferenceInfo->setState(infoState);

			long long conferenceInfoId = -1;
#ifdef HAVE_DB_STORAGE
			auto &mainDb = getCore()->getPrivate()->mainDb;
			if (mainDb) {
				lInfo()
				    << "Inserting conference information to database in order to be able to recreate the conference "
				    << *getConferenceAddress() << " in case of restart";
				conferenceInfoId = mainDb->insertConferenceInfo(conferenceInfo);
			}
#endif
			if (session) {
				auto callLog = session->getLog();
				if (callLog) {
					callLog->setConferenceInfo(conferenceInfo);
					callLog->setConferenceInfoId(conferenceInfoId);
				}
			}
			if (isEmpty) {
				setState(ConferenceInterface::State::TerminationPending);
			}
		} else {
			lWarning() << "Device with address " << address
			           << " is not allowed to update the conference because they have not been invited nor are "
			              "participants to conference "
			           << *getConferenceAddress() << " nor are the organizer";
		}
	}
}

void LocalConference::fillInvitedParticipantList(SalCallOp *op, bool cancelling) {
	mInvitedParticipants.clear();
	const auto &resourceList = op->getContentInRemote(ContentType::ResourceLists);
	if (resourceList && !resourceList.value().get().isEmpty()) {
		auto invitees = Utils::parseResourceLists(resourceList);
		mInvitedParticipants = invitees;
		if (!cancelling) {
			auto organizerNotFound =
			    std::find_if(mInvitedParticipants.begin(), mInvitedParticipants.end(), [this](const auto &invitee) {
				    return organizer->weakEqual(*invitee->getAddress());
			    }) == mInvitedParticipants.end();
			if (organizerNotFound && organizer) {
				Participant::Role role = Participant::Role::Speaker;
				lInfo() << "Setting role of organizer " << *organizer << " to " << role;
				auto organizerInfo = Factory::get()->createParticipantInfo(organizer);
				organizerInfo->setRole(role);
				mInvitedParticipants.push_back(organizerInfo);
			}
		}
	}
}
void LocalConference::configure(SalCallOp *op) {
	LinphoneCore *lc = getCore()->getCCore();
	bool admin = ((sal_address_has_param(op->getRemoteContactAddress(), "admin") &&
	               (strcmp(sal_address_get_param(op->getRemoteContactAddress(), "admin"), "1") == 0)));

	std::shared_ptr<ConferenceInfo> info = nullptr;
#ifdef HAVE_DB_STORAGE
	auto &mainDb = getCore()->getPrivate()->mainDb;
	if (mainDb) {
		info = getCore()->getPrivate()->mainDb->getConferenceInfoFromURI(Address::create(op->getTo()));
	}
#endif // HAVE_DB_STORAGE

	bool audioEnabled = true;
	std::string subject;
	time_t startTime = ms_time(NULL);
	time_t endTime = ms_time(NULL);

	time_t startTimeSdp = 0;
	time_t endTimeSdp = 0;

	const auto &remoteMd = op->getRemoteMediaDescription();
	const auto times = remoteMd->times;
	if (times.size() > 0) {
		startTimeSdp = times.front().first;
		endTimeSdp = times.front().second;
	}

	const bool createdConference = (info && info->isValidUri());
	// If start time or end time is not -1, then the client wants to update the conference
	const auto isUpdate = (admin && ((startTimeSdp != -1) || (endTimeSdp != -1)) && info);

	ConferenceParams::SecurityLevel securityLevel = ConferenceParams::SecurityLevel::None;
	if (createdConference && info) {
		securityLevel = info->getSecurityLevel();
	} else {
		const auto &toAddrStr = op->getTo();
		Address toAddr(toAddrStr);
		if (toAddr.hasUriParam(Conference::SecurityModeParameter)) {
			securityLevel = ConferenceParams::getSecurityLevelFromAttribute(
			    toAddr.getUriParamValue(Conference::SecurityModeParameter));
		}
	}
	confParams->setSecurityLevel(securityLevel);

	mMixerSession->setSecurityLevel(confParams->getSecurityLevel());

	if (isUpdate || (admin && !createdConference)) {
		// The following informations are retrieved from the received INVITE:
		// - start and end time from the SDP active time attribute
		// - conference active media:
		//    - if the SDP has at least one active audio stream, audio is enabled
		//    - if the core is a conference server, video is enabled
		// - Subject is got from the "Subject" header in the INVITE
		audioEnabled = (remoteMd->nbActiveStreamsOfType(SalAudio) > 0);
		if (!op->getSubject().empty()) {
			subject = op->getSubject();
		}
		organizer = Address::create(op->getFrom());

		startTime = startTimeSdp;
		if (startTime <= 0) {
			startTime = ms_time(NULL);
		}
		endTime = endTimeSdp;
		if (endTime <= 0) {
			endTime = -1;
		}
		fillInvitedParticipantList(op, false);
	} else if (info) {
		subject = info->getSubject();
		organizer = info->getOrganizerAddress();

		startTime = info->getDateTime();
		const auto duration = info->getDuration();
		if ((duration > 0) && (startTime >= 0)) {
			endTime = startTime + static_cast<time_t>(duration) * 60;
		} else {
			endTime = -1;
		}
		mInvitedParticipants = info->getParticipants();
	}

	auto videoEnabled = linphone_core_video_enabled(lc);
	if (videoEnabled && !linphone_core_conference_server_enabled(lc)) {
		lWarning() << "Video capability in a conference is not supported when a device that is not a server is hosting "
		              "a conference.";
		videoEnabled = false;
	}
	confParams->enableAudio(audioEnabled);
	confParams->enableVideo(videoEnabled);

	if (!subject.empty()) {
		confParams->setSubject(subject);
	}
	confParams->enableLocalParticipant(false);
	confParams->enableOneParticipantConference(true);
	confParams->setStatic(true);

	confParams->setStartTime(startTime);
	confParams->setEndTime(endTime);

	if (!isUpdate && !info) {
		// Set joining mode only when creating a conference
		bool immediateStart = (startTimeSdp < 0);
		const auto joiningMode =
		    (immediateStart) ? ConferenceParams::JoiningMode::DialOut : ConferenceParams::JoiningMode::DialIn;
		confParams->setJoiningMode(joiningMode);
	}

	if (info || admin) {
		MediaSessionParams msp;
		msp.enableAudio(audioEnabled);
		msp.enableVideo(videoEnabled);
		msp.getPrivate()->setInConference(true);
		msp.getPrivate()->setStartTime(startTime);
		msp.getPrivate()->setEndTime(endTime);

		std::shared_ptr<Address> conferenceAddress;
		if (info) {
			conferenceAddress = info->getUri();
		} else if (admin) {
			conferenceAddress = Address::create(op->getTo());
			shared_ptr<CallSession> session = getMe()->createSession(*this, &msp, true, nullptr);
			session->configure(LinphoneCallIncoming, nullptr, op, organizer, conferenceAddress);
		}
	}

	me->setRole(Participant::Role::Speaker);
	me->setAdmin(true);
	me->setFocus(true);

	if (createdConference) {
		const auto &conferenceAddress = info->getUri();
		setConferenceId(ConferenceId(conferenceAddress, conferenceAddress));
		setConferenceAddress(conferenceAddress);
	}

	if (isUpdate) {
		const auto &conferenceInfo = createOrGetConferenceInfo();
		auto meSession = getMe()->getSession();
		if (meSession) {
			auto callLog = meSession->getLog();
			if (callLog) {
				callLog->setConferenceInfo(conferenceInfo);
			}
		}
		updateConferenceInformation(op);
	}
}

std::list<std::shared_ptr<Address>> LocalConference::getAllowedAddresses() const {
	auto allowedAddresses = getInvitedAddresses();
	;
	auto organizerIt =
	    std::find_if(mInvitedParticipants.begin(), mInvitedParticipants.end(),
	                 [this](const auto &participant) { return participant->getAddress()->weakEqual(*organizer); });
	if (organizerIt == mInvitedParticipants.end()) {
		allowedAddresses.push_back(organizer);
	}
	return allowedAddresses;
}

void LocalConference::notifyStateChanged(LinphonePrivate::ConferenceInterface::State state) {
	// Call callbacks before calling listeners because listeners may change state
	linphone_core_notify_conference_state_changed(getCore()->getCCore(), toC(), (LinphoneConferenceState)getState());

	Conference::notifyStateChanged(state);
}

void LocalConference::confirmCreation() {

	if ((state != ConferenceInterface::State::Instantiated) && (state != ConferenceInterface::State::CreationPending)) {
		lError() << "Unable to confirm the creation of the conference in state " << state;
	}

	shared_ptr<MediaSession> session = dynamic_pointer_cast<MediaSession>(getMe()->getSession());

	if (session) {
		/* Assign a random conference address to this new conference, with domain
		 * set according to the proxy config used to receive the INVITE.
		 */
		auto account = session->getPrivate()->getDestAccount();
		if (!account) {
			const auto cAccount = linphone_core_get_default_account(getCore()->getCCore());
			if (cAccount) {
				account = Account::toCpp(cAccount)->getSharedFromThis();
			}
		}

		char confId[LinphonePrivate::MediaConference::LocalConference::confIdLength];
		if (account) {
			const auto accountParams = account->getAccountParams();
			std::shared_ptr<Address> conferenceAddress = accountParams->getIdentityAddress()->clone()->toSharedPtr();
			belle_sip_random_token(confId, sizeof(confId));
			conferenceAddress->setUriParam("conf-id", confId);
			setConferenceId(ConferenceId(conferenceAddress, conferenceAddress));
		}
		const_cast<LinphonePrivate::CallSessionParamsPrivate *>(L_GET_PRIVATE(session->getParams()))
		    ->setInConference(true);
		session->getPrivate()->setConferenceId(confId);

		/* We have to call initiateIncoming() and startIncomingNotification() in order to perform the first
		 * offer/answer, and make sure that the caller has compatible SDP offer. However, ICE creates problem here
		 * because the gathering is asynchronous, and is useless anyway because the MediaSession here will anyway
		 * terminate immediately by only two possibilities:
		 * - 488 if SDP offer is not compatible
		 * - or 302 if ok.
		 * We have no need to perform ICE gathering for this session, so we set the NatPolicy to nullptr.
		 */
		session->setNatPolicy(nullptr);
		session->initiateIncoming();
		session->startIncomingNotification(false);

		const auto &conferenceInfo = createOrGetConferenceInfo();
		long long conferenceInfoId = -1;
#ifdef HAVE_DB_STORAGE
		/// Method startIncomingNotification can move the conference to the CreationFailed state if the organizer
		/// doesn't have any of the codecs the server supports
		if (getState() != ConferenceInterface::State::CreationFailed) {
			// Store into DB after the start incoming notification in order to have a valid conference address being the
			// contact address of the call
			auto &mainDb = getCore()->getPrivate()->mainDb;
			if (mainDb) {
				const auto conferenceAddressStr = (getConferenceAddress() ? getConferenceAddress()->toString()
				                                                          : std::string("<address-not-defined>"));
				lInfo()
				    << "Inserting conference information to database in order to be able to recreate the conference "
				    << conferenceAddressStr << " in case of restart";
				conferenceInfoId = mainDb->insertConferenceInfo(conferenceInfo);
			}
		}
#endif
		auto callLog = session->getLog();
		if (callLog) {
			callLog->setConferenceInfo(conferenceInfo);
			callLog->setConferenceInfoId(conferenceInfoId);
		}

	} else {
		lError() << "Unable to confirm the creation of the conference because no session was created";
	}
}

std::shared_ptr<ConferenceInfo> LocalConference::createConferenceInfo() const {
	return createConferenceInfoWithCustomParticipantList(organizer, getFullParticipantList());
}

void LocalConference::finalizeCreation() {
	if (getState() == ConferenceInterface::State::CreationPending) {
		const std::shared_ptr<Address> &conferenceAddress = getConferenceAddress();
		setConferenceId(ConferenceId(conferenceAddress, conferenceAddress));
		shared_ptr<CallSession> session = me->getSession();
		if (session) {
			std::shared_ptr<ConferenceInfo> info = nullptr;
#ifdef HAVE_DB_STORAGE
			auto &mainDb = getCore()->getPrivate()->mainDb;
			if (mainDb) {
				info = getCore()->getPrivate()->mainDb->getConferenceInfoFromURI(getConferenceAddress());
			}
#endif // HAVE_DB_STORAGE
			const bool createdConference = (info && info->isValidUri());

			if (confParams->getJoiningMode() == ConferenceParams::JoiningMode::DialOut) {
				confParams->setStartTime(ms_time(NULL));
			}

			if (!createdConference) {
				auto addr = *conferenceAddress;
				addr.setParam("isfocus");
				if (session->getState() == CallSession::State::Idle) {
					lInfo() << " Scheduling redirection to [" << addr << "] for Call session [" << session << "]";
					getCore()->doLater([session, addr] { session->redirect(addr); });
				} else {
					session->redirect(addr);
				}
			} else {
				lInfo() << "Conference " << *conferenceAddress
				        << " has already been created therefore no need to carry out the redirection to its address";
			}
		} else {
			lError() << "Session of the me participant " << *me->getAddress() << " of conference " << *conferenceAddress
			         << " is not known therefore it is not possible to carry out the redirection";
		}
#ifdef HAVE_ADVANCED_IM
		if (eventHandler) {
			eventHandler->setConference(this);
		}
#endif // HAVE_ADVANCED_IM
	}
}

void LocalConference::subscribeReceived(shared_ptr<EventSubscribe> event) {
#ifdef HAVE_ADVANCED_IM
	if (eventHandler) {
		const auto ret = eventHandler->subscribeReceived(event);
		if (ret == 0) {
			// A client joins when the conference receives the SUBSCRIBE. This allows to ensure that no NOTIFY is missed
			// and we don't have to necessarely wait for the client reINVITE or ICE reINVITE to start sending NOTIFYs
			// regarding the conference to him/her
			const auto &participantAddress = event->getFrom();
			auto participant = findParticipant(participantAddress);
			if (participant) {
				const auto &contactAddr = event->getRemoteContact();
				auto device = participant->findDevice(contactAddr);
				if (device) {
					participantDeviceJoined(participant, device);
				}
			}
		}
		return;
	} else {
#endif // HAVE_ADVANCED_IM
		lInfo() << "Unable to accept SUBSCRIBE because conference event package (RFC 4575) is disabled or the SDK was "
		           "not compiled with ENABLE_ADVANCED_IM flag set to on";
#ifdef HAVE_ADVANCED_IM
	}
#endif // HAVE_ADVANCED_IM
	event->deny(LinphoneReasonNotAcceptable);
}

void LocalConference::setParticipantAdminStatus(const shared_ptr<Participant> &participant, bool isAdmin) {
	if (isAdmin != participant->isAdmin()) {
		participant->setAdmin(isAdmin);
		time_t creationTime = time(nullptr);
		notifyParticipantSetAdmin(creationTime, false, participant, isAdmin);
	}
}

void LocalConference::onConferenceTerminated(const std::shared_ptr<Address> &addr) {
#ifdef HAVE_ADVANCED_IM
	if (eventHandler) {
		eventHandler->setConference(nullptr);
	}
#endif // HAVE_ADVANCED_IM
	Conference::onConferenceTerminated(addr);
}

void LocalConference::addLocalEndpoint() {
	if (confParams->localParticipantEnabled()) {
		StreamMixer *mixer = mMixerSession->getMixerByType(SalAudio);
		if (mixer) {
			mixer->enableLocalParticipant(true);
			// Get ssrc of me because it must be sent to participants through NOTIFY
			auto audioMixer = dynamic_cast<MS2AudioMixer *>(mixer);
			auto audioStream = audioMixer->getAudioStream();
			auto meSsrc = audio_stream_get_send_ssrc(audioStream);
			for (auto &device : me->getDevices()) {
				device->setSsrc(LinphoneStreamTypeAudio, meSsrc);
			}
		}

		if (confParams->videoEnabled()) {
			mixer = mMixerSession->getMixerByType(SalVideo);
			if (mixer) {
				mixer->enableLocalParticipant(true);
#ifdef VIDEO_ENABLED
				auto videoMixer = dynamic_cast<MS2VideoMixer *>(mixer);
				auto videoStream = videoMixer->getVideoStream();
				auto meSsrc = media_stream_get_send_ssrc(&videoStream->ms);
				for (auto &device : me->getDevices()) {
					device->setSsrc(LinphoneStreamTypeVideo, meSsrc);
					videoMixer->setLocalParticipantLabel(device->getLabel(LinphoneStreamTypeVideo));
				}
#endif // VIDEO_ENABLED
				VideoControlInterface *vci = getVideoControlInterface();
				if (vci) {
					vci->setNativePreviewWindowId(getCore()->getCCore()->preview_window_id);
					vci->setNativeWindowId(getCore()->getCCore()->video_window_id);
				}
			}
		}

		if (!isIn()) {
			mIsIn = true;
			time_t creationTime = time(nullptr);
			notifyParticipantAdded(creationTime, false, getMe());
			for (auto &device : me->getDevices()) {
				notifyParticipantDeviceAdded(creationTime, false, getMe(), device);
			}
		}
	}
}

int LocalConference::inviteAddresses(const list<std::shared_ptr<Address>> &addresses,
                                     const LinphoneCallParams *params) {

	const auto &coreCurrentCall = getCore()->getCurrentCall();
	const bool startingConference = (getState() == ConferenceInterface::State::CreationPending);

	const auto &outputDevice = (coreCurrentCall) ? coreCurrentCall->getOutputAudioDevice() : nullptr;
	const auto &inputDevice = (coreCurrentCall) ? coreCurrentCall->getInputAudioDevice() : nullptr;

	auto lc = getCore()->getCCore();

	for (const auto &address : addresses) {
		std::shared_ptr<Call> call = nullptr;

		/*
		 * In the case of a conference server, it is enough to look if there is already a participant with the same
		 * address as the one searched. If this is the case, then pick the first device (if there is one) and search the
		 * call on the list held by the core. A non-conference server may be wishing to add an already running call to a
		 * conference, therefore the search is done through the remote address. A use case is the following:
		 * - A has establishehd individual calls towards B and C and wants to add them to a conference hosted on its
		 * device
		 * - A can call inviteAddresses({B,C}, params) and we should not start any new call
		 * Note that this scenario is not possible for a conference server as it is a passive component.
		 */
		if (linphone_core_conference_server_enabled(lc)) {
			auto participant = findParticipant(address);
			if (participant) {
				const auto &devices = participant->getDevices();
				if (!devices.empty()) {
					const auto &device = devices.front();
					if (!device->getCallId().empty()) {
						call = getCore()->getCallByCallId(device->getCallId());
					} else if (device->getSession()) {
						const auto &session = device->getSession();
						const auto &calls = getCore()->getCalls();
						auto it = std::find_if(calls.cbegin(), calls.cend(), [&session](const auto &c) {
							return (c->getActiveSession() == session);
						});
						if (it != calls.cend()) {
							call = (*it);
						}
					}
				}
			}
		} else {
			call = getCore()->getCallByRemoteAddress(address);
		}
		if (!call) {
			/* Start a new call by indicating that it has to be put into the conference directly */
			LinphoneCallParams *new_params;
			if (params) {
				new_params = _linphone_call_params_copy(params);
			} else {
				new_params = linphone_core_create_call_params(lc, nullptr);
				linphone_call_params_enable_video(new_params, confParams->videoEnabled());
			}

			linphone_call_params_set_in_conference(new_params, TRUE);
			linphone_call_params_set_start_time(new_params, confParams->getStartTime());

			const std::shared_ptr<Address> &conferenceAddress = getConferenceAddress();
			const string &confId = conferenceAddress->getUriParamValue("conf-id");
			linphone_call_params_set_conference_id(new_params, confId.c_str());

			call = Call::toCpp(linphone_core_invite_address_with_params_2(
			                       lc, address->toC(), new_params, L_STRING_TO_C(confParams->getSubject()), NULL))
			           ->getSharedFromThis();

			if (!confParams->getAccount()) {
				// Set proxy configuration used for the conference
				auto callAccount = call->getDestAccount();
				if (callAccount) {
					confParams->setAccount(callAccount);
				} else {
					confParams->setAccount(
					    Account::toCpp(linphone_core_lookup_known_account(lc, address->toC()))->getSharedFromThis());
				}
			}

			tryAddMeDevice();

			if (!call) {
				lError() << "LocalConference::inviteAddresses(): could not invite participant";
			} else {
				addParticipant(call);
				auto participant = findParticipant(address);
				participant->setPreserveSession(false);
			}
			linphone_call_params_unref(new_params);
		} else {
			/* There is already a call to this address, so simply join it to the local conference if not already done */
			if (!call->getCurrentParams()->getPrivate()->getInConference()) {
				addParticipant(call);
				auto participant = findParticipant(address);
				participant->setPreserveSession(true);
			}
		}
		/* If the local participant is not yet created, created it and it to the conference */
		addLocalEndpoint();
		call->setConference(getSharedFromThis());
	}

	// If current call is not NULL and the conference is in the creating pending state or instantied, then try to change
	// audio route to keep the one currently used
	if (startingConference) {
		if (outputDevice) {
			setOutputAudioDevice(outputDevice);
		}
		if (inputDevice) {
			setInputAudioDevice(inputDevice);
		}
	}

	return 0;
}

int LocalConference::participantDeviceAlerting(const std::shared_ptr<LinphonePrivate::CallSession> &session) {
	const std::shared_ptr<Address> &remoteAddress = session->getRemoteAddress();
	std::shared_ptr<LinphonePrivate::Participant> p = findParticipant(remoteAddress);
	if (p) {
		std::shared_ptr<ParticipantDevice> device = p->findDevice(session);
		if (device) {
			return participantDeviceAlerting(p, device);
		} else {
			lDebug() << "Participant alerting: Unable to find device with session " << session
			         << " among devices of participant " << p->getAddress()->toString() << " of conference "
			         << *getConferenceAddress();
		}
	}
	return -1;
}

int LocalConference::participantDeviceAlerting(
    BCTBX_UNUSED(const std::shared_ptr<LinphonePrivate::Participant> &participant),
    const std::shared_ptr<LinphonePrivate::ParticipantDevice> &device) {
	lInfo() << "Device " << *device->getAddress() << " changed state to alerting";
	device->updateMediaCapabilities();
	device->updateStreamAvailabilities();
	device->setState(ParticipantDevice::State::Alerting);
	return 0;
}

int LocalConference::participantDeviceJoined(const std::shared_ptr<LinphonePrivate::CallSession> &session) {
	const std::shared_ptr<Address> &remoteAddress = session->getRemoteAddress();
	std::shared_ptr<LinphonePrivate::Participant> p = findParticipant(remoteAddress);
	if (p) {
		std::shared_ptr<ParticipantDevice> device = p->findDevice(session);
		if (device) {
			return participantDeviceJoined(p, device);
		} else {
			lDebug() << "Participant joined: Unable to find device with session " << session
			         << " among devices of participant " << p->getAddress()->toString() << " of conference "
			         << *getConferenceAddress();
		}
	}
	return -1;
}

int LocalConference::participantDeviceJoined(
    BCTBX_UNUSED(const std::shared_ptr<LinphonePrivate::Participant> &participant),
    const std::shared_ptr<LinphonePrivate::ParticipantDevice> &device) {
	int success = -1;
	const auto mediaCapabilitiesChanged = device->updateMediaCapabilities();
	if ((!mediaCapabilitiesChanged.empty() || (device->getState() != ParticipantDevice::State::Present)) &&
	    (getState() == ConferenceInterface::State::Created)) {
		lInfo() << "Device " << *device->getAddress() << " joined conference " << *getConferenceAddress();
		device->updateStreamAvailabilities();
		device->setState(ParticipantDevice::State::Present);
		return 0;
	}
	return success;
}

int LocalConference::participantDeviceLeft(const std::shared_ptr<LinphonePrivate::CallSession> &session) {
	const std::shared_ptr<Address> &remoteAddress = session->getRemoteAddress();
	std::shared_ptr<LinphonePrivate::Participant> p = findParticipant(remoteAddress);
	if (p) {
		std::shared_ptr<ParticipantDevice> device = p->findDevice(session);
		if (device) {
			return participantDeviceLeft(p, device);
		} else {
			lWarning() << "Participant left: Unable to find device with session " << session
			           << " among devices of participant " << p->getAddress()->toString() << " of conference "
			           << *getConferenceAddress();
		}
	}
	return -1;
}

int LocalConference::participantDeviceLeft(
    BCTBX_UNUSED(const std::shared_ptr<LinphonePrivate::Participant> &participant),
    const std::shared_ptr<LinphonePrivate::ParticipantDevice> &device) {
	int success = -1;
	const auto mediaCapabilitiesChanged = device->updateMediaCapabilities();
	if ((!mediaCapabilitiesChanged.empty() || (device->getState() != ParticipantDevice::State::OnHold)) &&
	    (getState() == ConferenceInterface::State::Created)) {
		lInfo() << "Device " << *device->getAddress() << " left conference " << *getConferenceAddress();
		device->updateStreamAvailabilities();
		device->setState(ParticipantDevice::State::OnHold);
		return 0;
	}
	return success;
}
int LocalConference::participantDeviceMediaCapabilityChanged(
    const std::shared_ptr<LinphonePrivate::CallSession> &session) {
	const std::shared_ptr<Address> &remoteAddress = session->getRemoteAddress();
	std::shared_ptr<LinphonePrivate::Participant> p = findParticipant(remoteAddress);
	int success = -1;
	if (p) {
		std::shared_ptr<ParticipantDevice> device = p->findDevice(session);
		if (device) {
			success = participantDeviceMediaCapabilityChanged(p, device);
		} else {
			lWarning() << "Participant media capability changed: Unable to find device with session " << session
			           << " among devices of participant " << p->getAddress()->toString() << " of conference "
			           << *getConferenceAddress();
		}
	}
	return success;
}

int LocalConference::participantDeviceMediaCapabilityChanged(const std::shared_ptr<Address> &addr) {
	std::shared_ptr<LinphonePrivate::Participant> p = findParticipant(addr);
	int success = -1;
	for (const auto &d : p->getDevices()) {
		success = participantDeviceMediaCapabilityChanged(p, d);
	}
	return success;
}

int LocalConference::participantDeviceMediaCapabilityChanged(
    const std::shared_ptr<LinphonePrivate::Participant> &participant,
    const std::shared_ptr<LinphonePrivate::ParticipantDevice> &device) {
	int success = -1;
	const auto mediaCapabilitiesChanged = device->updateMediaCapabilities();
	if (!mediaCapabilitiesChanged.empty() &&
	    ((getState() == ConferenceInterface::State::CreationPending) ||
	     (getState() == ConferenceInterface::State::Created)) &&
	    (device->getState() == ParticipantDevice::State::Present)) {
		lInfo() << "Device " << *device->getAddress() << " in conference " << *getConferenceAddress()
		        << " changed its media capabilities";
		device->updateStreamAvailabilities();
		time_t creationTime = time(nullptr);
		notifyParticipantDeviceMediaCapabilityChanged(creationTime, false, participant, device);
		return 0;
	}
	return success;
}

int LocalConference::participantDeviceSsrcChanged(const std::shared_ptr<LinphonePrivate::CallSession> &session,
                                                  const LinphoneStreamType type,
                                                  uint32_t ssrc) {
	const std::shared_ptr<Address> &remoteAddress = session->getRemoteAddress();
	std::shared_ptr<LinphonePrivate::Participant> p = findParticipant(remoteAddress);
	int success = -1;
	if (p) {
		std::shared_ptr<ParticipantDevice> device = p->findDevice(session);
		if (device) {
			bool updated = device->setSsrc(type, ssrc);
			if (updated) {
				lInfo() << "Setting " << std::string(linphone_stream_type_to_string(type))
				        << " ssrc of participant device " << device->getAddress()->toString() << " in conference "
				        << *getConferenceAddress() << " to " << ssrc;
				time_t creationTime = time(nullptr);
				notifyParticipantDeviceMediaCapabilityChanged(creationTime, false, p, device);
			} else {
				lInfo() << "Leaving unchanged ssrc of participant device " << device->getAddress()->toString()
				        << " in conference " << *getConferenceAddress() << " whose value is " << ssrc;
			}
			return 0;
		}
	}
	lInfo() << "Unable to set " << std::string(linphone_stream_type_to_string(type)) << " ssrc to " << ssrc
	        << " because participant device with session " << session << " cannot be found in conference "
	        << *getConferenceAddress();
	return success;
}

int LocalConference::participantDeviceSsrcChanged(const std::shared_ptr<LinphonePrivate::CallSession> &session,
                                                  uint32_t audioSsrc,
                                                  uint32_t videoSsrc) {
	const std::shared_ptr<Address> &remoteAddress = session->getRemoteAddress();
	std::shared_ptr<LinphonePrivate::Participant> p = findParticipant(remoteAddress);
	int success = -1;
	if (p) {
		std::shared_ptr<ParticipantDevice> device = p->findDevice(session);
		if (device) {
			if (device->setSsrc(LinphoneStreamTypeAudio, audioSsrc) ||
			    device->setSsrc(LinphoneStreamTypeVideo, videoSsrc)) {
				time_t creationTime = time(nullptr);
				notifyParticipantDeviceMediaCapabilityChanged(creationTime, false, p, device);
			} else {
				lInfo() << "Leaving unchanged ssrcs of participant device " << device->getAddress()->toString()
				        << " in conference " << *getConferenceAddress() << " whose values are";
				lInfo() << "- audio -> " << audioSsrc;
				lInfo() << "- video -> " << videoSsrc;
			}
			return 0;
		}
	}
	lInfo() << "Unable to set audio ssrc to " << audioSsrc << " and video ssrc to " << videoSsrc
	        << " because participant device with session " << session << " cannot be found in conference "
	        << *getConferenceAddress();
	return success;
}

int LocalConference::getParticipantDeviceVolume(const std::shared_ptr<LinphonePrivate::ParticipantDevice> &device) {
	MS2AudioMixer *mixer = dynamic_cast<MS2AudioMixer *>(mMixerSession->getMixerByType(SalAudio));
	if (mixer) {
		MSAudioConference *conf = mixer->getAudioConference();
		return ms_audio_conference_get_participant_volume(conf, device->getSsrc(LinphoneStreamTypeAudio));
	}

	return AUDIOSTREAMVOLUMES_NOT_FOUND;
}

bool LocalConference::dialOutAddresses(const std::list<std::shared_ptr<Address>> &addressList) {
	auto new_params = linphone_core_create_call_params(getCore()->getCCore(), nullptr);
	linphone_call_params_enable_video(new_params, confParams->videoEnabled());

	linphone_call_params_set_in_conference(new_params, TRUE);

	const std::shared_ptr<Address> &conferenceAddress = getConferenceAddress();
	const string &confId = conferenceAddress->getUriParamValue("conf-id");
	linphone_call_params_set_conference_id(new_params, confId.c_str());

	std::list<std::shared_ptr<Address>> addresses = getInvitedAddresses();
	// Add participants already in the conference to the list of addresses if they are not part of the invitees
	for (const auto &p : getParticipants()) {
		const auto &pAddress = p->getAddress();
		auto pIt = std::find_if(addresses.begin(), addresses.end(),
		                        [&pAddress](const auto &address) { return (pAddress->weakEqual(*address)); });
		if (pIt == addresses.end()) {
			addresses.push_back(pAddress);
		}
	}

	auto resourceList = Content::create();
	resourceList->setBodyFromUtf8(Utils::getResourceLists(addresses));
	resourceList->setContentType(ContentType::ResourceLists);
	resourceList->setContentDisposition(ContentDisposition::RecipientList);
	if (linphone_core_content_encoding_supported(getCore()->getCCore(), "deflate")) {
		resourceList->setContentEncoding("deflate");
	}
	if (!resourceList->isEmpty()) {
		L_GET_CPP_PTR_FROM_C_OBJECT(new_params)->addCustomContent(resourceList);
	}

	auto sipfrag = Content::create();
	const auto organizerUri = organizer->getUri();
	sipfrag->setBodyFromLocale("From: <" + organizerUri.toString() + ">");
	sipfrag->setContentType(ContentType::SipFrag);
	L_GET_CPP_PTR_FROM_C_OBJECT(new_params)->addCustomContent(sipfrag);
	auto success = (inviteAddresses(addressList, new_params) == 0);
	linphone_call_params_unref(new_params);
	return success;
}

bool LocalConference::addParticipants(const std::list<std::shared_ptr<Call>> &calls) {
	const auto &coreCurrentCall = getCore()->getCurrentCall();
	const bool startingConference = (getState() == ConferenceInterface::State::CreationPending);
	const auto &outputDevice = (coreCurrentCall) ? coreCurrentCall->getOutputAudioDevice() : nullptr;
	const auto &inputDevice = (coreCurrentCall) ? coreCurrentCall->getInputAudioDevice() : nullptr;

	bool success = Conference::addParticipants(calls);
	// If current call is not NULL and the conference is in the creating pending state or instantied, then try to change
	// audio route to keep the one currently used Do not change audio route if participant addition is not successful
	if (success && startingConference) {
		if (outputDevice) {
			setOutputAudioDevice(outputDevice);
		}
		if (inputDevice) {
			setInputAudioDevice(inputDevice);
		}
	}

	return success;
}

bool LocalConference::addParticipants(const std::list<std::shared_ptr<Address>> &addresses) {
	return Conference::addParticipants(addresses);
}

bool LocalConference::addParticipantDevice(std::shared_ptr<LinphonePrivate::Call> call) {
	bool success = Conference::addParticipantDevice(call);
	if (success) {
		call->setConference(getSharedFromThis());
		auto session = call->getActiveSession();
		auto device = findParticipantDevice(session);
		if (device) {
			device->setJoiningMethod((call->getDirection() == LinphoneCallIncoming)
			                             ? ParticipantDevice::JoiningMethod::DialedIn
			                             : ParticipantDevice::JoiningMethod::DialedOut);
			char label[LinphonePrivate::Conference::labelLength];
			belle_sip_random_token(label, sizeof(label));
			device->setLabel(label, LinphoneStreamTypeAudio);
			belle_sip_random_token(label, sizeof(label));
			device->setLabel(label, LinphoneStreamTypeVideo);
			auto op = session->getPrivate()->getOp();
			auto displayName = L_C_TO_STRING(sal_address_get_display_name(
			    (call->getDirection() == LinphoneCallIncoming) ? op->getFromAddress() : op->getToAddress()));
			if (!displayName.empty()) {
				device->setName(displayName);
			}
			const auto &p = device->getParticipant();
			if (p) {
				time_t creationTime = time(nullptr);
				notifyParticipantDeviceAdded(creationTime, false, p, device);
			}
		}
	}
	return success;
}

bool LocalConference::tryAddMeDevice() {
	if (confParams->localParticipantEnabled() && me->getDevices().empty() && confParams->getAccount()) {
		const auto &contactAddress = confParams->getAccount()->getContactAddress();
		if (contactAddress) {
			std::shared_ptr<Address> devAddr = contactAddress->clone()->toSharedPtr();
			auto meDev = me->addDevice(devAddr);
			const auto &meSession = me->getSession();

			char label[Conference::labelLength];
			belle_sip_random_token(label, sizeof(label));
			meDev->setLabel(label, LinphoneStreamTypeAudio);
			belle_sip_random_token(label, sizeof(label));
			meDev->setLabel(label, LinphoneStreamTypeVideo);
			meDev->setSession(meSession);
			meDev->setJoiningMethod(ParticipantDevice::JoiningMethod::FocusOwner);
			meDev->setState(ParticipantDevice::State::Present);

			// Initialize media directions
			meDev->setStreamCapability(
			    (confParams->audioEnabled() ? LinphoneMediaDirectionSendRecv : LinphoneMediaDirectionInactive),
			    LinphoneStreamTypeAudio);
			meDev->setStreamCapability(
			    (confParams->videoEnabled() ? LinphoneMediaDirectionSendRecv : LinphoneMediaDirectionInactive),
			    LinphoneStreamTypeVideo);
			meDev->setStreamCapability(
			    (confParams->chatEnabled() ? LinphoneMediaDirectionSendRecv : LinphoneMediaDirectionInactive),
			    LinphoneStreamTypeText);

			meDev->updateStreamAvailabilities();

			return true;
		}
	}
	return false;
}

bool LocalConference::addParticipant(std::shared_ptr<LinphonePrivate::Call> call) {

	const auto &remoteAddress = call->getRemoteAddress();
	if (linphone_call_params_get_in_conference(linphone_call_get_current_params(call->toC()))) {
		lError() << "Call (local address " << call->getLocalAddress()->toString() << " remote address "
		         << (remoteAddress ? remoteAddress->toString() : "Unknown") << ") is already in conference "
		         << *getConferenceAddress();
		return false;
	}

	if (confParams->getParticipantListType() == ConferenceParams::ParticipantListType::Closed) {
		const auto allowedAddresses = getAllowedAddresses();
		auto p = std::find_if(allowedAddresses.begin(), allowedAddresses.end(),
		                      [&remoteAddress](const auto &address) { return (remoteAddress->weakEqual(*address)); });
		if (p == allowedAddresses.end()) {
			lError() << "Unable to add call (local address " << call->getLocalAddress()->toString()
			         << " remote address " << (remoteAddress ? remoteAddress->toString() : "Unknown")
			         << ") because participant " << *remoteAddress
			         << " is not in the list of allowed participants of conference " << *getConferenceAddress();
			LinphoneErrorInfo *ei = linphone_error_info_new();
			linphone_error_info_set(ei, NULL, LinphoneReasonUnknown, 403, "Call forbidden to join the conference",
			                        NULL);
			call->terminate(ei);
			linphone_error_info_unref(ei);
			return false;
		}
	}

	const auto initialState = getState();
	const auto dialout = (confParams->getJoiningMode() == ConferenceParams::JoiningMode::DialOut);
	// If conference must start immediately, then the organizer will call the conference server and the other
	// participants will be dialed out
	if ((initialState == ConferenceInterface::State::CreationPending) && dialout &&
	    !remoteAddress->weakEqual(*organizer)) {
		lError() << "The conference must immediately start (start time: " << confParams->getStartTime()
		         << " end time: " << confParams->getEndTime() << "). Unable to add participant "
		         << remoteAddress->toString()
		         << " because participants will be dialed out by the conference server as soon as " << organizer
		         << " dials in";
		return false;
	}

#if 0
	if (!isConferenceStarted()) {
		lError() << "Unable to add call (local address " << call->getLocalAddress()->toString() << " remote address " <<  (remoteAddress ? remoteAddress->toString() : "Unknown") << ") because participant " << *remoteAddress << " is not in the list of allowed participants of conference " << *getConferenceAddress();
		LinphoneErrorInfo *ei = linphone_error_info_new();
		linphone_error_info_set(ei, NULL, LinphoneReasonUnknown, 403, "Conference not started yet", NULL);
		call->terminate(ei);
		linphone_error_info_unref(ei);
		return false;
	}

	if (isConferenceEnded()) {
		lError() << "Unable to add call (local address " << call->getLocalAddress()->toString() << " remote address " <<  (remoteAddress ? remoteAddress->toString() : "Unknown") << ") because participant " << *remoteAddress << " is not in the list of allowed participants of conference " << *getConferenceAddress();
		LinphoneErrorInfo *ei = linphone_error_info_new();
		linphone_error_info_set(ei, NULL, LinphoneReasonUnknown, 403, "Conference already terminated", NULL);
		call->terminate(ei);
		linphone_error_info_unref(ei);
		return false;
	}
#endif

	const std::shared_ptr<Address> &conferenceAddress = getConferenceAddress();
	const string &confId = conferenceAddress->getUriParamValue("conf-id");
	const string &callConfId = call->getConferenceId();

	const auto &coreCurrentCall = getCore()->getCurrentCall();
	const bool startingConference = (getState() == ConferenceInterface::State::CreationPending);

	const auto &outputDevice = (coreCurrentCall) ? coreCurrentCall->getOutputAudioDevice() : nullptr;
	const auto &inputDevice = (coreCurrentCall) ? coreCurrentCall->getInputAudioDevice() : nullptr;

	// Add participant only if creation is successful or call was previously part of the conference
	bool canAddParticipant =
	    ((callConfId.compare(confId) == 0) || (getState() == ConferenceInterface::State::CreationPending) ||
	     (getState() == ConferenceInterface::State::Created));

	if (canAddParticipant) {
		auto session = call->getMediaSession();
		const auto &remoteContactAddress = session->getRemoteContactAddress();
		LinphoneCallState state = static_cast<LinphoneCallState>(call->getState());

		auto participantDevice = (remoteContactAddress && remoteContactAddress->isValid())
		                             ? findParticipantDevice(session->getRemoteAddress(), remoteContactAddress)
		                             : nullptr;
		if (participantDevice) {
			auto deviceSession = participantDevice->getSession();
			if (deviceSession) {
				if (session == deviceSession) {
					lWarning() << "Try to add again a participant device with session " << session;
					return false;
				} else {
					lInfo() << "Already found a participant device with address " << *remoteContactAddress
					        << ". Recreating it";
					deviceSession->terminate();
				}
			}
		}

		if (!confParams->getAccount()) {
			// Set proxy configuration used for the conference
			auto callAccount = call->getDestAccount();
			if (callAccount) {
				confParams->setAccount(callAccount);
			} else {
				confParams->setAccount(
				    Account::toCpp(linphone_core_lookup_known_account(getCore()->getCCore(),
				                                                      linphone_call_get_to_address(call->toC())))
				        ->getSharedFromThis());
			}
		}

		// Get contact address here because it may be modified by a change in the local parameters. As the participant
		// enters the conference, in fact attributes conf-id and isfocus are added later on (based on local parameters)
		// therefore there is no way to know if the remote client already knew that the call was in a conference or not.
		auto contactAddress = session->getContactAddress();
		tryAddMeDevice();

		if (!mMixerSession) {
			mMixerSession.reset(new MixerSession(*getCore().get()));
		}

		// Add participant to the conference participant list
		switch (state) {
			case LinphoneCallOutgoingInit:
			case LinphoneCallOutgoingProgress:
			case LinphoneCallOutgoingRinging:
			case LinphoneCallIncomingReceived:
			case LinphoneCallPausing:
			case LinphoneCallPaused:
			case LinphoneCallResuming:
			case LinphoneCallStreamsRunning: {
				if (call->toC() == linphone_core_get_current_call(getCore()->getCCore()))
					L_GET_PRIVATE_FROM_C_OBJECT(getCore()->getCCore())->setCurrentCall(nullptr);
				mMixerSession->joinStreamsGroup(session->getStreamsGroup());
				/*
				 * Modifying the MediaSession's params directly is a bit hacky.
				 */
				const_cast<LinphonePrivate::MediaSessionParamsPrivate *>(L_GET_PRIVATE(call->getParams()))
				    ->setInConference(true);
				const_cast<LinphonePrivate::MediaSessionParamsPrivate *>(L_GET_PRIVATE(call->getParams()))
				    ->setConferenceId(confId);
				const_cast<LinphonePrivate::MediaSessionParamsPrivate *>(L_GET_PRIVATE(call->getParams()))
				    ->setStartTime(confParams->getStartTime());
				const_cast<LinphonePrivate::MediaSessionParamsPrivate *>(L_GET_PRIVATE(call->getParams()))
				    ->setEndTime(confParams->getEndTime());
				if (getCurrentParams().videoEnabled()) {
					if (getCurrentParams().localParticipantEnabled()) {
						const_cast<LinphonePrivate::MediaSessionParams *>(call->getParams())->enableVideo(true);
					} else {
						if (call->getRemoteParams()) {
							const_cast<LinphonePrivate::MediaSessionParams *>(call->getParams())
							    ->enableVideo(call->getRemoteParams()->videoEnabled());
						}
					}
				} else {
					const_cast<LinphonePrivate::MediaSessionParams *>(call->getParams())->enableVideo(false);
				}

				bool success = Conference::addParticipant(call);

				const auto &participant = findParticipant(session->getRemoteAddress());
				LinphoneMediaDirection audioDirection = LinphoneMediaDirectionInactive;
				LinphoneMediaDirection videoDirection = LinphoneMediaDirectionInactive;
				if (participant) {
					const auto &role = participant->getRole();
					switch (role) {
						case Participant::Role::Speaker:
							audioDirection = LinphoneMediaDirectionSendRecv;
							videoDirection = LinphoneMediaDirectionSendRecv;
							break;
						case Participant::Role::Listener:
							audioDirection = LinphoneMediaDirectionSendOnly;
							videoDirection = LinphoneMediaDirectionSendOnly;
							break;
						case Participant::Role::Unknown:
							audioDirection = LinphoneMediaDirectionInactive;
							videoDirection = LinphoneMediaDirectionInactive;
							break;
					}

					auto &mainDb = getCore()->getPrivate()->mainDb;
					if (success && conferenceAddress && mainDb) {
						auto conferenceInfo = mainDb->getConferenceInfoFromURI(conferenceAddress);
						if (conferenceInfo) {
							const auto &organizerAddress = conferenceInfo->getOrganizerAddress();
							if (organizerAddress && organizerAddress->weakEqual(*participant->getAddress())) {
								setParticipantAdminStatus(participant, true);
							}
						}
					}
				}

				const_cast<LinphonePrivate::MediaSessionParams *>(call->getParams())->setAudioDirection(audioDirection);
				const_cast<LinphonePrivate::MediaSessionParams *>(call->getParams())->setVideoDirection(videoDirection);
			}

			break;
			default:
				lError() << "Call " << call << " (local address " << *call->getLocalAddress() << " remote address "
				         << (remoteAddress ? remoteAddress->toString() : "Unknown") << ") is in state "
				         << Utils::toString(call->getState())
				         << ", hence it cannot be added to the conference right now";
				return false;
				break;
		}

		// Update call
		auto device = findParticipantDevice(session);
		switch (state) {
			case LinphoneCallPausing:
				// Call cannot be resumed immediately, hence delay it until next state change
				session->delayResume();
				break;
			case LinphoneCallOutgoingInit:
			case LinphoneCallOutgoingProgress:
			case LinphoneCallOutgoingRinging:
			case LinphoneCallIncomingReceived:
				break;
			case LinphoneCallPaused:
				// Conference resumes call that previously paused in order to add the participant
				getCore()->doLater([call] { call->resume(); });
				break;
			case LinphoneCallStreamsRunning:
			case LinphoneCallResuming: {
				if (state == LinphoneCallStreamsRunning) {
					// Calling enter here because update will lock sound resources
					enter();
				}
				if (contactAddress && contactAddress->isValid() && !contactAddress->hasParam("isfocus")) {
					lInfo() << "Call " << call << " (local address " << *call->getLocalAddress() << " remote address "
					        << (remoteAddress ? remoteAddress->toString() : "Unknown") << " because contact address "
					        << (contactAddress ? contactAddress->toString() : "Unknown")
					        << " has not 'isfocus' parameter";

					getCore()->doLater([call, session] {
						const MediaSessionParams *params = session->getMediaParams();
						MediaSessionParams *currentParams = params->clone();
						call->update(currentParams);
						delete currentParams;
					});
				}
			} break;
			default:
				lError() << "Call " << call << " (local address " << *call->getLocalAddress() << " remote address "
				         << (remoteAddress ? remoteAddress->toString() : "Unknown") << ") is in state "
				         << Utils::toString(call->getState())
				         << ", hence the call cannot be updated following it becoming part of the conference";
				return false;
				break;
		}

		// If current call is not NULL and the conference is in the creating pending state or instantied, then try to
		// change audio route to keep the one currently used
		if (startingConference) {
			if (outputDevice) {
				setOutputAudioDevice(outputDevice);
			}
			if (inputDevice) {
				setInputAudioDevice(inputDevice);
			}
		}
		setState(ConferenceInterface::State::Created);

		auto op = session->getPrivate()->getOp();
		auto resourceList = op ? op->getContentInRemote(ContentType::ResourceLists) : nullopt;
		bool isEmpty = resourceList ? resourceList.value().get().isEmpty() : true;

		// If no resource list is provided in the INVITE, there is no need to call participants
		if ((initialState == ConferenceInterface::State::CreationPending) && dialout && !isEmpty) {
			list<std::shared_ptr<Address>> addresses;
			for (auto &participant : mInvitedParticipants) {
				const auto &addr = participant->getAddress();
				// Do not invite organizer as it is already dialing in
				if (*addr != *organizer) {
					addresses.push_back(addr);
				}
			}
			dialOutAddresses(addresses);
		}

		return true;
	}

	lError() << "Unable to add call (local address " << call->getLocalAddress()->toString() << " remote address "
	         << (remoteAddress ? remoteAddress->toString() : "Unknown") << ") to conference "
	         << *getConferenceAddress();
	return false;
}

bool LocalConference::addParticipant(const std::shared_ptr<Address> &participantAddress) {
	auto participantInfo = Factory::get()->createParticipantInfo(participantAddress);
	// Participants invited after the start of a conference through the address can only listen to it
	participantInfo->setRole(Participant::Role::Listener);
	return addParticipant(participantInfo);
}

bool LocalConference::addParticipant(const std::shared_ptr<ParticipantInfo> &info) {
#if 0
	if (!isConferenceEnded() && isConferenceStarted()) {
#endif
	const auto initialState = getState();
	if ((initialState == ConferenceInterface::State::CreationPending) ||
	    (initialState == ConferenceInterface::State::Created)) {

		const auto allowedAddresses = getAllowedAddresses();
		const auto &participantAddress = info->getAddress();
		auto p =
		    std::find_if(allowedAddresses.begin(), allowedAddresses.end(), [&participantAddress](const auto &address) {
			    return (participantAddress->weakEqual(*address));
		    });
		if (p == allowedAddresses.end()) {
			auto participantInfo = info->clone()->toSharedPtr();
			participantInfo->setSequenceNumber(-1);
			mInvitedParticipants.push_back(participantInfo);
		}

		std::list<std::shared_ptr<Address>> addressesList{participantAddress};
		return dialOutAddresses(addressesList);
	}
#if 0
	} else {
		const auto & endTime = confParams->getEndTime();
		const auto & startTime = confParams->getStartTime();
		const auto now = time(NULL);
		lError() << "Could not add participant " << *participantAddress << " to the conference because the conference " << *getConferenceAddress() << " is not active right now.";
		if (startTime >= 0) {
			lError() << "Expected start time (" << startTime << "): " << ctime(&startTime);
		} else {
			lError() << "Expected start time: none";
		}
		if (endTime >= 0) {
			lError() << "Expected end time (" << endTime << "): " << ctime(&endTime);
		} else {
			lError() << "Expected end time: none";
		}
		lError() << "Now: " << ctime(&now);
		return false;

	}
#endif
	return false;
}

void LocalConference::setLocalParticipantStreamCapability(const LinphoneMediaDirection &direction,
                                                          const LinphoneStreamType type) {
	if (confParams->localParticipantEnabled() && !me->getDevices().empty() && confParams->getAccount() &&
	    (type != LinphoneStreamTypeUnknown)) {
		const auto &contactAddress = confParams->getAccount()->getContactAddress();
		if (contactAddress) {
			std::shared_ptr<Address> devAddr = contactAddress->clone()->toSharedPtr();
			const auto &meDev = me->findDevice(devAddr);
			if (meDev) {
				lInfo() << "Setting direction of stream of type " << std::string(linphone_stream_type_to_string(type))
				        << " to " << std::string(linphone_media_direction_to_string(direction)) << " of device "
				        << meDev->getAddress()->toString();
				const auto mediaChanged = meDev->setStreamCapability(direction, type);
				meDev->updateStreamAvailabilities();
				for (const auto &p : getParticipants()) {
					for (const auto &d : p->getDevices()) {
						d->updateStreamAvailabilities();
					}
				}

				if (mediaChanged) {
					time_t creationTime = time(nullptr);
					notifyParticipantDeviceMediaCapabilityChanged(creationTime, false, me, meDev);
				}
			} else {
				lError() << "Unable to find device with address " << devAddr->toString()
				         << " among those in the local participant " << me->getAddress()->toString();
			}
		}
	}
}

bool LocalConference::finalizeParticipantAddition(std::shared_ptr<LinphonePrivate::Call> call) {
	const auto &newParticipantSession = call->getMediaSession();
	const auto &device = findParticipantDevice(newParticipantSession);
	if (device) {
		const auto deviceState = device->getState();
		if (deviceState == ParticipantDevice::State::Joining) {
			const std::shared_ptr<Address> &remoteAddress = call->getRemoteAddress();
			const auto &p = findParticipant(remoteAddress);
			if (device && p) {
				participantDeviceJoined(p, device);
			}
		} else if (deviceState == ParticipantDevice::State::ScheduledForJoining) {
			device->setState(ParticipantDevice::State::Joining);
			auto contactAddress = newParticipantSession->getContactAddress();

			if (contactAddress && contactAddress->isValid() && !contactAddress->hasParam("isfocus")) {
				getCore()->doLater([this, call] {
					const std::shared_ptr<Address> &conferenceAddress = getConferenceAddress();
					const string &confId = conferenceAddress->getUriParamValue("conf-id");

					LinphoneCallParams *params = linphone_core_create_call_params(getCore()->getCCore(), call->toC());
					linphone_call_params_set_in_conference(params, TRUE);
					linphone_call_params_set_conference_id(params, confId.c_str());
					linphone_call_params_set_start_time(params, confParams->getStartTime());
					linphone_call_params_set_end_time(params, confParams->getEndTime());
					if (getCurrentParams().videoEnabled()) {
						linphone_call_params_enable_video(
						    params, linphone_call_params_video_enabled(linphone_call_get_remote_params(call->toC())));
					} else {
						linphone_call_params_enable_video(params, FALSE);
					}

					linphone_call_update(call->toC(), params);
					linphone_call_params_unref(params);
				});
			}
		}
	}

	return true;
}

int LocalConference::removeParticipant(const std::shared_ptr<LinphonePrivate::CallSession> &session,
                                       const bool preserveSession) {
	int err = 0;

	auto op = session->getPrivate()->getOp();
	shared_ptr<Call> call = getCore()->getCallByCallId(op->getCallId());
	if (call) {
		if (linphone_call_get_conference(call->toC()) != toC()) {
			const auto &remoteAddress = call->getRemoteAddress();
			lError() << "Call (local address " << call->getLocalAddress()->toString() << " remote address "
			         << (remoteAddress ? remoteAddress->toString() : "Unknown") << ") is not part of conference "
			         << *getConferenceAddress();
			return -1;
		}
	}

	CallSession::State sessionState = session->getState();

	const std::shared_ptr<Address> &remoteAddress = session->getRemoteAddress();
	std::shared_ptr<LinphonePrivate::Participant> participant = findParticipant(remoteAddress);
	if (participant) {
		Conference::removeParticipant(session, preserveSession);
		mMixerSession->unjoinStreamsGroup(
		    static_pointer_cast<LinphonePrivate::MediaSession>(session)->getStreamsGroup());
	} else {
		if ((sessionState != LinphonePrivate::CallSession::State::Released) &&
		    (sessionState != LinphonePrivate::CallSession::State::End)) {
			lError() << "Trying to remove participant " << *session->getRemoteAddress() << " with session " << session
			         << " which is not part of conference " << *getConferenceAddress();
		}
		return -1;
	}

	if (getState() != ConferenceInterface::State::TerminationPending) {

		// Detach call from conference
		if (call) {
			call->setConference(nullptr);
		}

		if (participant->getPreserveSession()) {
			// If the session is already paused,then send an update to kick the participant out of the conference, pause
			// the call otherwise
			if (sessionState == CallSession::State::Paused) {
				lInfo() << "Updating call to notify of conference removal.";
				const MediaSessionParams *params =
				    static_pointer_cast<LinphonePrivate::MediaSession>(session)->getMediaParams();
				MediaSessionParams *currentParams = params->clone();
				currentParams->getPrivate()->setInConference(FALSE);
				currentParams->getPrivate()->setConferenceId("");
				err = static_pointer_cast<LinphonePrivate::MediaSession>(session)->updateFromConference(currentParams);
				delete currentParams;
			} else if ((sessionState != CallSession::State::End) && (sessionState != CallSession::State::Released)) {
				lInfo() << "Pause call to notify of conference removal.";
				/* Kick the session out of the conference by moving to the Paused state. */
				const_cast<LinphonePrivate::MediaSessionParamsPrivate *>(
				    L_GET_PRIVATE(static_pointer_cast<LinphonePrivate::MediaSession>(session)->getMediaParams()))
				    ->setInConference(false);
				const_cast<LinphonePrivate::MediaSessionParamsPrivate *>(
				    L_GET_PRIVATE(static_pointer_cast<LinphonePrivate::MediaSession>(session)->getMediaParams()))
				    ->setConferenceId("");
				err = static_pointer_cast<LinphonePrivate::MediaSession>(session)->pauseFromConference();
			}
		} else {
			// Terminate session (i.e. send a BYE) as per RFC
			// This is the default behaviour
			if (sessionState != LinphonePrivate::CallSession::State::End) {
				err = static_pointer_cast<LinphonePrivate::MediaSession>(session)->terminate();
			}
		}

		/*
		 * Handle the case where only the local participant and a unique remote participant are remaining.
		 * In this case, if the session linked to the participant has to be preserved after the conference, then destroy
		 * the conference and let these two participants to connect directly thanks to a simple call. Indeed, the
		 * conference adds latency and processing that is useless to do for 1-1 conversation.
		 */
		if (!confParams->oneParticipantConferenceEnabled() && (getParticipantCount() == 1) && (!preserveSession)) {
			std::shared_ptr<LinphonePrivate::Participant> remainingParticipant = participants.front();
			const bool lastParticipantPreserveSession = remainingParticipant->getPreserveSession();
			auto &devices = remainingParticipant->getDevices();
			if (lastParticipantPreserveSession && (devices.size() == 1)) {

				std::shared_ptr<LinphonePrivate::MediaSession> lastSession =
				    static_pointer_cast<LinphonePrivate::MediaSession>(devices.front()->getSession());

				if (lastSession) {
					lInfo() << "Participant [" << remainingParticipant << "] with "
					        << lastSession->getRemoteAddress()->toString() << " is the last call in conference "
					        << *getConferenceAddress() << ", we will reconnect directly to it.";

					const MediaSessionParams *params = lastSession->getMediaParams();
					// If only one participant is in the conference, the conference is destroyed.
					if (isIn()) {
						lInfo() << "Updating call to notify of conference removal.";
						MediaSessionParams *currentParams = params->clone();
						// If the local participant is in, then an update is sent in order to notify that the call is
						// exiting the conference
						currentParams->getPrivate()->setInConference(FALSE);
						currentParams->getPrivate()->setConferenceId("");
						err = lastSession->updateFromConference(currentParams);
						delete currentParams;
					} else {
						// If the local participant is not in, the call is paused as the local participant is busy
						const_cast<LinphonePrivate::MediaSessionParamsPrivate *>(L_GET_PRIVATE(params))
						    ->setInConference(false);

						err = lastSession->pauseFromConference();
					}
				}

				setState(ConferenceInterface::State::TerminationPending);

				leave();

				/* invoke removeParticipant() recursively to remove this last participant. */
				bool success = Conference::removeParticipant(remainingParticipant);
				mMixerSession->unjoinStreamsGroup(lastSession->getStreamsGroup());

				if (lastSession) {
					// Detach call from conference
					auto lastOp = lastSession->getPrivate()->getOp();
					if (lastOp) {
						shared_ptr<Call> lastSessionCall = getCore()->getCallByCallId(lastOp->getCallId());
						if (lastSessionCall) {
							lastSessionCall->setConference(nullptr);
						}
					}
				}

				checkIfTerminated();
				return success ? 0 : -1;
			}
		}
	}

	// If call that we are trying to remove from the conference is in paused by remote state, then it temporarely left
	// the conference therefore it must not be terminated
	if (sessionState != LinphonePrivate::CallSession::State::PausedByRemote) {
		checkIfTerminated();
	}

	return err ? 0 : -1;
}

int LocalConference::removeParticipant(const std::shared_ptr<Address> &addr) {
	const std::shared_ptr<LinphonePrivate::Participant> participant = findParticipant(addr);
	if (!participant) return -1;
	return removeParticipant(participant) ? 0 : -1;
}

bool LocalConference::removeParticipant(const std::shared_ptr<LinphonePrivate::Participant> &participant) {
	const auto devices = participant->getDevices();
	bool success = true;
	if (devices.size() > 0) {
		for (const auto &d : devices) {
			success &= (removeParticipant(d->getSession(), false) == 0);
		}
	} else {
		lInfo() << "Remove participant with address " << *participant->getAddress() << " from conference "
		        << *getConferenceAddress();
		participants.remove(participant);
		time_t creationTime = time(nullptr);
		notifyParticipantRemoved(creationTime, false, participant);
		success = true;
	}
	return success;
}

void LocalConference::checkIfTerminated() {
	if (getParticipantCount() == 0) {
		if (!confParams->isStatic()) {
			leave();
			if (getState() == ConferenceInterface::State::TerminationPending) {
				setState(ConferenceInterface::State::Terminated);
			} else {
				setState(ConferenceInterface::State::TerminationPending);
#ifdef HAVE_ADVANCED_IM
				bool_t eventLogEnabled = linphone_config_get_bool(linphone_core_get_config(getCore()->getCCore()),
				                                                  "misc", "conference_event_log_enabled", TRUE);
				if (!eventLogEnabled || !eventHandler) {
#endif // HAVE_ADVANCED_IM
					setState(ConferenceInterface::State::Terminated);
#ifdef HAVE_ADVANCED_IM
				}
#endif // HAVE_ADVANCED_IM
			}
		}
		mMixerSession.reset();
	}
}

void LocalConference::chooseAnotherAdminIfNoneInConference() {
	if (participants.empty() == false) {
		const auto adminParticipant = std::find_if(participants.cbegin(), participants.cend(),
		                                           [&](const auto &p) { return (p->isAdmin() == true); });
		// If not admin participant is found
		if (adminParticipant == participants.cend()) {
			setParticipantAdminStatus(participants.front(), true);
			lInfo() << this << ": New admin designated is " << *(participants.front());
		}
	}
}

/* ConferenceInterface */
void LocalConference::setSubject(const std::string &subject) {
	if (subject.compare(getUtf8Subject()) != 0) {
		Conference::setSubject(subject);
		time_t creationTime = time(nullptr);
		notifySubjectChanged(creationTime, false, subject);
	}
}

#ifndef _MSC_VER
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-parameter"
#endif // _MSC_VER
void LocalConference::subscriptionStateChanged(shared_ptr<EventSubscribe> event, LinphoneSubscriptionState state) {
#ifdef HAVE_ADVANCED_IM
	if (eventHandler) {
		eventHandler->subscriptionStateChanged(event, state);
	} else {
#endif // HAVE_ADVANCED_IM
		lInfo() << "Unable to handle subscription state change because conference event package (RFC 4575) is disabled "
		           "or the SDK was not compiled with ENABLE_ADVANCED_IM flag set to on";
#ifdef HAVE_ADVANCED_IM
	}
#endif // HAVE_ADVANCED_IM
}
#ifndef _MSC_VER
#pragma GCC diagnostic pop
#endif // _MSC_VER

int LocalConference::terminate() {
	const auto conferenceAddressStr =
	    (getConferenceAddress() ? getConferenceAddress()->toString() : std::string("<address-not-defined>"));
	lInfo() << "Terminate conference " << conferenceAddressStr;
	// Take a ref because the conference may be immediately go to deleted state if terminate is called when there are 0
	// participants
	const auto ref = getSharedFromThis();
	setState(ConferenceInterface::State::TerminationPending);

	size_t noDevices = 0;
	auto participantIt = participants.begin();
	while (participantIt != participants.end()) {
		auto participant = *participantIt;
		const auto devices = participant->getDevices();
		noDevices += devices.size();
		participantIt++;
		if (devices.size() > 0) {
			for (const auto &d : devices) {
				std::shared_ptr<LinphonePrivate::MediaSession> session =
				    static_pointer_cast<LinphonePrivate::MediaSession>(d->getSession());
				if (session) {
					lInfo() << "Terminating session of participant device " << d->getAddress();
					session->terminate();
				}
			}
		} else {
			removeParticipant(participant);
		}
	}

	const auto zeroDevices = (noDevices == 0);
	if (zeroDevices
#ifdef HAVE_ADVANCED_IM
	    || !eventHandler
#endif // HAVE_ADVANCED_IM
	) {
		setState(ConferenceInterface::State::Terminated);
	}

	return 0;
}

int LocalConference::enter() {

	if (confParams->localParticipantEnabled()) {
		if (linphone_core_sound_resources_locked(getCore()->getCCore())) return -1;
		if (linphone_core_get_current_call(getCore()->getCCore()))
			linphone_call_pause(linphone_core_get_current_call(getCore()->getCCore()));

		const auto &meAddress = me->getAddress();
		lInfo() << *meAddress << " is rejoining conference " << *getConferenceAddress();
		organizer = meAddress;
		addLocalEndpoint();
		if (me->getDevices().size() > 0) {
			participantDeviceJoined(me, me->getDevices().front());
		}
	}

	return 0;
}

void LocalConference::removeLocalEndpoint() {
	mMixerSession->enableLocalParticipant(false);

	if (isIn()) {
		mIsIn = false;

		time_t creationTime = time(nullptr);
		for (auto &device : me->getDevices()) {
			notifyParticipantDeviceRemoved(creationTime, false, getMe(), device);
		}
		notifyParticipantRemoved(creationTime, false, getMe());
	}
}

void LocalConference::leave() {
	if (isIn()) {
		lInfo() << getMe()->getAddress() << " is leaving conference " << *getConferenceAddress();
		if (me->getDevices().size() > 0) {
			participantDeviceLeft(me, me->getDevices().front());
		}
		removeLocalEndpoint();
	}
}

bool LocalConference::validateNewParameters(const LinphonePrivate::ConferenceParams &newConfParams) const {
	if (!confParams) {
		return true;
	}

	if (confParams->getConferenceFactoryAddress() != newConfParams.getConferenceFactoryAddress()) {
		lError() << "Factory address change is not allowed: actual " << confParams->getConferenceFactoryAddress()
		         << " new value " << newConfParams.getConferenceFactoryAddress();
		return false;
	}

	if (*confParams->getConferenceAddress() != *newConfParams.getConferenceAddress()) {
		lError() << "Conference address change is not allowed: actual " << *confParams->getConferenceAddress()
		         << " new value " << *newConfParams.getConferenceAddress();
		return false;
	}

	if (confParams->getSecurityLevel() != newConfParams.getSecurityLevel()) {
		lError() << "Conference security level change is not allowed: actual " << confParams->getSecurityLevel()
		         << " new value " << newConfParams.getSecurityLevel();
		return false;
	}

	return true;
}

bool LocalConference::update(const LinphonePrivate::ConferenceParamsInterface &newParameters) {
	/* Only adding or removing video is supported. */
	bool previousVideoEnablement = confParams->videoEnabled();
	bool previousAudioEnablement = confParams->audioEnabled();
	bool previousChatEnablement = confParams->chatEnabled();
	const LinphonePrivate::ConferenceParams &newConfParams = static_cast<const ConferenceParams &>(newParameters);
	if (!validateNewParameters(newConfParams)) {
		return false;
	}
	confParams = ConferenceParams::create(newConfParams);

	if (!linphone_core_conference_server_enabled(getCore()->getCCore()) && confParams->videoEnabled()) {
		lWarning() << "Video capability in a conference is not supported when a device that is not a server is hosting "
		              "a conference.";
		confParams->enableVideo(false);
	}

	// Update endpoints only if audio or video settings have changed
	if ((confParams->videoEnabled() != previousVideoEnablement) ||
	    (confParams->audioEnabled() != previousAudioEnablement)) {
		/* Don't forget the local participant. For simplicity, a removeLocalEndpoint()/addLocalEndpoint() does the job.
		 */
		removeLocalEndpoint();
		addLocalEndpoint();
	}
	if ((confParams->chatEnabled() != previousChatEnablement) ||
	    (confParams->videoEnabled() != previousVideoEnablement) ||
	    (confParams->audioEnabled() != previousAudioEnablement)) {
		time_t creationTime = time(nullptr);
		notifyAvailableMediaChanged(creationTime, false, getMediaCapabilities());
	}

	bool mediaChanged = false;
	for (auto &meDev : me->getDevices()) {
		mediaChanged = false;
		mediaChanged |= meDev->setStreamCapability(
		    (confParams->audioEnabled() ? LinphoneMediaDirectionSendRecv : LinphoneMediaDirectionInactive),
		    LinphoneStreamTypeAudio);
		mediaChanged |= meDev->setStreamCapability(
		    (confParams->videoEnabled() ? LinphoneMediaDirectionSendRecv : LinphoneMediaDirectionInactive),
		    LinphoneStreamTypeVideo);
		mediaChanged |= meDev->setStreamCapability(
		    (confParams->chatEnabled() ? LinphoneMediaDirectionSendRecv : LinphoneMediaDirectionInactive),
		    LinphoneStreamTypeText);

		if (mediaChanged) {
			time_t creationTime = time(nullptr);
			notifyParticipantDeviceMediaCapabilityChanged(creationTime, false, me, meDev);
		}
	}
	return true;
}

int LocalConference::startRecording(const char *path) {
	MS2AudioMixer *mixer =
	    mMixerSession ? dynamic_cast<MS2AudioMixer *>(mMixerSession->getMixerByType(SalAudio)) : nullptr;
	if (mixer) {
		mixer->setRecordPath(path);
		mixer->startRecording();
		// TODO: error reporting is absent.
	} else {
		lError() << "LocalConference::startRecording(): no audio mixer.";
		return -1;
	}
	return 0;
}

bool LocalConference::isIn() const {
	return mIsIn;
}

const std::shared_ptr<Address> LocalConference::getOrganizer() const {
	return organizer;
}

AudioControlInterface *LocalConference::getAudioControlInterface() const {
	return mMixerSession ? dynamic_cast<AudioControlInterface *>(mMixerSession->getMixerByType(SalAudio)) : nullptr;
}

VideoControlInterface *LocalConference::getVideoControlInterface() const {
	return mMixerSession ? dynamic_cast<VideoControlInterface *>(mMixerSession->getMixerByType(SalVideo)) : nullptr;
}

AudioStream *LocalConference::getAudioStream() {
	MS2AudioMixer *mixer =
	    mMixerSession ? dynamic_cast<MS2AudioMixer *>(mMixerSession->getMixerByType(SalAudio)) : nullptr;
	return mixer ? mixer->getAudioStream() : nullptr;
}

void LocalConference::notifyFullState() {
	++lastNotify;
	Conference::notifyFullState();
}

std::shared_ptr<Call> LocalConference::getCall() const {
	return nullptr;
}

void LocalConference::callStateChangedCb(LinphoneCore *lc,
                                         LinphoneCall *call,
                                         LinphoneCallState cstate,
                                         BCTBX_UNUSED(const char *message)) {
	LinphoneCoreVTable *vtable = linphone_core_get_current_vtable(lc);
	LocalConference *conf = (LocalConference *)linphone_core_v_table_get_user_data(vtable);
	auto cppCall = Call::toCpp(call)->getSharedFromThis();
	if (conf && conf->getSharedFromThis() == cppCall->getConference()) {
		const auto &session = cppCall->getActiveSession();
		const std::shared_ptr<Address> &remoteAddress = cppCall->getRemoteAddress();
		switch (cstate) {
			case LinphoneCallStateOutgoingRinging:
				participantDeviceAlerting(session);
				break;
			case LinphoneCallStateConnected:
				if (getState() == ConferenceInterface::State::Created) {
					enter();
				}
				break;
			case LinphoneCallStateStreamsRunning: {
				if (!addParticipantDevice(cppCall)) {
					// If the participant is already in the conference
					const auto &participant = findParticipant(remoteAddress);
					const auto &device = findParticipantDevice(session);
					const auto &deviceState =
					    device ? device->getState() : ParticipantDevice::State::ScheduledForJoining;
					auto remoteContactAddress = session->getRemoteContactAddress();
					if (participant) {
						if (device) {
							const auto deviceAddr = device->getAddress();
							const std::shared_ptr<Address> newDeviceAddress = remoteContactAddress;
							if (deviceAddr->toStringOrdered() != newDeviceAddress->toStringOrdered()) {
								// The remote contact address of the device changed during the call. This may be caused
								// by a call that started before the registration was completed
								lInfo() << "Updating address of participant device " << device << " with session "
								        << device->getSession() << " from " << *deviceAddr << " to "
								        << *newDeviceAddress;
								auto otherDevice = participant->findDevice(newDeviceAddress);
								// If a device with the same address has been found, then remove it from the participant
								// list and copy subscription event. Otherwise, notify that it has been added
								if (otherDevice && (otherDevice != device)) {
									time_t creationTime = time(nullptr);
									device->setTimeOfDisconnection(creationTime);
									device->setDisconnectionMethod(ParticipantDevice::DisconnectionMethod::Booted);
									const auto reason("Reason: SIP;text=address changed");
									device->setDisconnectionReason(reason);
									// As the device changed address, notify that the current device has been removed
									notifyParticipantDeviceRemoved(creationTime, false, participant, device);

									if (!device->getConferenceSubscribeEvent() &&
									    otherDevice->getConferenceSubscribeEvent()) {
										// Move subscription event pointer to device.
										// This is required because if the call starts before the registration process,
										// the device address may have an unresolved address whereas the subscription
										// may have started after the device is fully registered, hence the full device
										// address is known.
										device->setConferenceSubscribeEvent(otherDevice->getConferenceSubscribeEvent());
										otherDevice->setConferenceSubscribeEvent(nullptr);
									}
									// Delete device having the same address
									// First remove device from the device list to avoid sending a participant device
									// removed
									participant->removeDevice(otherDevice->getAddress());
									auto otherDeviceSession = otherDevice->getSession();
									if (otherDeviceSession) {
										otherDeviceSession->terminate();
									}

									creationTime = time(nullptr);
									device->setAddress(remoteContactAddress);
									notifyParticipantDeviceMediaCapabilityChanged(creationTime, false, participant,
									                                              device);
								} else {
									device->setAddress(remoteContactAddress);
									participantDeviceJoined(session);
								}
							}
						}
					} else {
						lError() << "Unable to update admin status and device address as no participant with address "
						         << *remoteAddress << " has been found in conference " << *getConferenceAddress();
					}
					if (device) {
						if (deviceState == ParticipantDevice::State::Present) {
							participantDeviceMediaCapabilityChanged(session);
						} else if ((deviceState == ParticipantDevice::State::Joining) ||
						           (deviceState == ParticipantDevice::State::ScheduledForJoining)) {
							// Participants complete their addition to a conference when the call goes back to the
							// StreamsRunning state
							if (!cppCall->mediaInProgress() ||
							    !!!linphone_config_get_int(linphone_core_get_config(getCore()->getCCore()), "sip",
							                               "update_call_when_ice_completed", TRUE)) {
								// Participants complete their addition to a conference when the call goes back to the
								// StreamsRunning state
								finalizeParticipantAddition(cppCall);
							} else {
								auto contactAddress = session->getContactAddress();
								if (contactAddress && contactAddress->isValid() &&
								    contactAddress->hasParam("isfocus")) {
									device->setState(ParticipantDevice::State::Joining);
								}
							}
						} else {
							participantDeviceJoined(session);
						}
					} else {
						lError() << "Unable to update device with address " << *remoteContactAddress
						         << " because it was not found in conference " << *getConferenceAddress();
					}
				}
			} break;
			case LinphoneCallStatePausedByRemote:
				// The participant temporarely left the conference and put its call in pause
				// If a call in a local conference is paused by remote, it means that the remote participant temporarely
				// left the call, hence notify that no audio and video is available
				lInfo() << "Call in conference has been put on hold by remote device, hence participant "
				        << *remoteAddress << " temporarely left conference " << *getConferenceAddress();
				participantDeviceLeft(session);
				break;
			case LinphoneCallStateUpdatedByRemote: {
				// If the participant is already in the conference
				const auto &device = findParticipantDevice(session);
				const auto &deviceState = device ? device->getState() : ParticipantDevice::State::ScheduledForJoining;
				if (session && device &&
				    ((deviceState == ParticipantDevice::State::Present) ||
				     (deviceState == ParticipantDevice::State::Joining))) {
					const auto op = session->getPrivate()->getOp();
					// The remote participant requested to change subject
					if (sal_custom_header_find(op->getRecvCustomHeaders(), "Subject")) {
						const auto &subject = op->getSubject();
						auto protocols = Utils::parseCapabilityDescriptor(device->getCapabilityDescriptor());
						auto conferenceProtocol = protocols.find("conference");
						if (((conferenceProtocol != protocols.end()) &&
						     (conferenceProtocol->second >= Utils::Version(1, 0))) ||
						    !CallSession::isPredefinedSubject(subject)) {
							// Handle subject change
							lInfo() << "conference " << *getConferenceAddress() << " changed subject to \"" << subject
							        << "\"";
							setSubject(subject);
						}
					}
				}
			} break;
			case LinphoneCallStateEnd:
			case LinphoneCallStateError:
				lInfo() << "Removing terminated call (local address " << *session->getLocalAddress()
				        << " remote address " << *remoteAddress << ") from conference " << this << " ("
				        << *getConferenceAddress() << ")";
				if (session->getErrorInfo() &&
				    (linphone_error_info_get_reason(session->getErrorInfo()) == LinphoneReasonBusy)) {
					removeParticipantDevice(session);
				} else {
					removeParticipant(session, false);
				}
				break;
			default:
				break;
		}
	}
}

void LocalConference::transferStateChangedCb(LinphoneCore *lc,
                                             LinphoneCall *transfered,
                                             BCTBX_UNUSED(LinphoneCallState new_call_state)) {
	LinphoneCoreVTable *vtable = linphone_core_get_current_vtable(lc);
	LocalConference *conf = (LocalConference *)linphone_core_v_table_get_user_data(vtable);
	auto cppCall = Call::toCpp(transfered)->getSharedFromThis();
	if (conf && conf->findParticipantDevice(cppCall->getActiveSession())) {
		lInfo() << "LocalConference::" << __func__ << " not implemented";
	}
}

shared_ptr<ConferenceParticipantEvent> LocalConference::notifyParticipantAdded(
    time_t creationTime, const bool isFullState, const std::shared_ptr<Participant> &participant) {
	// Increment last notify before notifying participants so that the delta can be calculated correctly
	++lastNotify;
	return Conference::notifyParticipantAdded(creationTime, isFullState, participant);
}

shared_ptr<ConferenceParticipantEvent> LocalConference::notifyParticipantRemoved(
    time_t creationTime, const bool isFullState, const std::shared_ptr<Participant> &participant) {
	if (getState() != ConferenceInterface::State::TerminationPending) {
		// Increment last notify before notifying participants so that the delta can be calculated correctly
		++lastNotify;
		return Conference::notifyParticipantRemoved(creationTime, isFullState, participant);
	}

	return nullptr;
}

shared_ptr<ConferenceParticipantEvent> LocalConference::notifyParticipantSetAdmin(
    time_t creationTime, const bool isFullState, const std::shared_ptr<Participant> &participant, bool isAdmin) {
	// Increment last notify before notifying participants so that the delta can be calculated correctly
	++lastNotify;
	return Conference::notifyParticipantSetAdmin(creationTime, isFullState, participant, isAdmin);
}

shared_ptr<ConferenceSubjectEvent>
LocalConference::notifySubjectChanged(time_t creationTime, const bool isFullState, const std::string subject) {
	// Increment last notify before notifying participants so that the delta can be calculated correctly
	++lastNotify;
	return Conference::notifySubjectChanged(creationTime, isFullState, subject);
}

shared_ptr<ConferenceAvailableMediaEvent> LocalConference::notifyAvailableMediaChanged(
    time_t creationTime, const bool isFullState, const std::map<ConferenceMediaCapabilities, bool> mediaCapabilities) {
	// Increment last notify before notifying participants so that the delta can be calculated correctly
	++lastNotify;
	return Conference::notifyAvailableMediaChanged(creationTime, isFullState, mediaCapabilities);
}

shared_ptr<ConferenceParticipantDeviceEvent>
LocalConference::notifyParticipantDeviceAdded(time_t creationTime,
                                              const bool isFullState,
                                              const std::shared_ptr<Participant> &participant,
                                              const std::shared_ptr<ParticipantDevice> &participantDevice) {
	// Increment last notify before notifying participants so that the delta can be calculated correctly
	++lastNotify;
	return Conference::notifyParticipantDeviceAdded(creationTime, isFullState, participant, participantDevice);
}

shared_ptr<ConferenceParticipantDeviceEvent>
LocalConference::notifyParticipantDeviceRemoved(time_t creationTime,
                                                const bool isFullState,
                                                const std::shared_ptr<Participant> &participant,
                                                const std::shared_ptr<ParticipantDevice> &participantDevice) {
	// Increment last notify before notifying participants so that the delta can be calculated correctly
	if ((getState() != ConferenceInterface::State::TerminationPending)) {
		++lastNotify;
		// Send notify only if it is not in state TerminationPending and:
		// - there are two or more participants in the conference
		return Conference::notifyParticipantDeviceRemoved(creationTime, isFullState, participant, participantDevice);
	}
	return nullptr;
}

shared_ptr<ConferenceParticipantDeviceEvent>
LocalConference::notifyParticipantDeviceStateChanged(time_t creationTime,
                                                     const bool isFullState,
                                                     const std::shared_ptr<Participant> &participant,
                                                     const std::shared_ptr<ParticipantDevice> &participantDevice) {
	// Increment last notify before notifying participants so that the delta can be calculated correctly
	++lastNotify;
	return Conference::notifyParticipantDeviceStateChanged(creationTime, isFullState, participant, participantDevice);
}

shared_ptr<ConferenceParticipantDeviceEvent> LocalConference::notifyParticipantDeviceMediaCapabilityChanged(
    time_t creationTime,
    const bool isFullState,
    const std::shared_ptr<Participant> &participant,
    const std::shared_ptr<ParticipantDevice> &participantDevice) {
	// Increment last notify before notifying participants so that the delta can be calculated correctly
	++lastNotify;
	return Conference::notifyParticipantDeviceMediaCapabilityChanged(creationTime, isFullState, participant,
	                                                                 participantDevice);
}

} // end of namespace MediaConference

LINPHONE_END_NAMESPACE