summaryrefslogtreecommitdiffstats
path: root/channels/rdpgfx/client/rdpgfx_main.c
blob: dd59c8b235aa78cd9c3f5a0d94cb3f3a3e564aa4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
/**
 * FreeRDP: A Remote Desktop Protocol Implementation
 * Graphics Pipeline Extension
 *
 * Copyright 2013-2014 Marc-Andre Moreau <marcandre.moreau@gmail.com>
 * Copyright 2015 Thincast Technologies GmbH
 * Copyright 2015 DI (FH) Martin Haimberger <martin.haimberger@thincast.com>
 * Copyright 2016 Thincast Technologies GmbH
 * Copyright 2016 Armin Novak <armin.novak@thincast.com>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <freerdp/config.h>

#include <winpr/assert.h>

#include <winpr/crt.h>
#include <winpr/wlog.h>
#include <winpr/print.h>
#include <winpr/synch.h>
#include <winpr/thread.h>
#include <winpr/stream.h>
#include <winpr/sysinfo.h>
#include <winpr/cmdline.h>
#include <winpr/collections.h>

#include <freerdp/addin.h>
#include <freerdp/channels/log.h>

#include "rdpgfx_common.h"
#include "rdpgfx_codec.h"

#include "rdpgfx_main.h"

#define TAG CHANNELS_TAG("rdpgfx.client")

static BOOL delete_surface(const void* key, void* value, void* arg)
{
	const UINT16 id = (UINT16)(uintptr_t)(key);
	RdpgfxClientContext* context = arg;
	RDPGFX_DELETE_SURFACE_PDU pdu = { 0 };

	WINPR_UNUSED(value);
	pdu.surfaceId = id - 1;

	if (context)
	{
		UINT error = CHANNEL_RC_OK;
		IFCALLRET(context->DeleteSurface, error, context, &pdu);

		if (error)
		{
			WLog_ERR(TAG, "context->DeleteSurface failed with error %" PRIu32 "", error);
		}
	}
	return TRUE;
}

static void free_surfaces(RdpgfxClientContext* context, wHashTable* SurfaceTable)
{
	HashTable_Foreach(SurfaceTable, delete_surface, context);
}

static void evict_cache_slots(RdpgfxClientContext* context, UINT16 MaxCacheSlots, void** CacheSlots)
{
	WINPR_ASSERT(CacheSlots);
	for (UINT16 index = 0; index < MaxCacheSlots; index++)
	{
		if (CacheSlots[index])
		{
			RDPGFX_EVICT_CACHE_ENTRY_PDU pdu = { 0 };
			pdu.cacheSlot = (UINT16)index + 1;

			if (context && context->EvictCacheEntry)
			{
				context->EvictCacheEntry(context, &pdu);
			}

			CacheSlots[index] = NULL;
		}
	}
}

/**
 * Function description
 *
 * @return 0 on success, otherwise a Win32 error code
 */
static UINT rdpgfx_send_caps_advertise_pdu(RdpgfxClientContext* context,
                                           const RDPGFX_CAPS_ADVERTISE_PDU* pdu)
{
	UINT error = CHANNEL_RC_OK;
	RDPGFX_HEADER header = { 0 };
	RDPGFX_PLUGIN* gfx = NULL;
	GENERIC_CHANNEL_CALLBACK* callback = NULL;
	wStream* s = NULL;

	WINPR_ASSERT(pdu);
	WINPR_ASSERT(context);

	gfx = (RDPGFX_PLUGIN*)context->handle;

	if (!gfx || !gfx->base.listener_callback)
		return ERROR_BAD_ARGUMENTS;

	callback = gfx->base.listener_callback->channel_callback;

	header.flags = 0;
	header.cmdId = RDPGFX_CMDID_CAPSADVERTISE;
	header.pduLength = RDPGFX_HEADER_SIZE + 2;

	for (UINT16 index = 0; index < pdu->capsSetCount; index++)
	{
		const RDPGFX_CAPSET* capsSet = &(pdu->capsSets[index]);
		header.pduLength += RDPGFX_CAPSET_BASE_SIZE + capsSet->length;
	}

	DEBUG_RDPGFX(gfx->log, "SendCapsAdvertisePdu %" PRIu16 "", pdu->capsSetCount);
	s = Stream_New(NULL, header.pduLength);

	if (!s)
	{
		WLog_ERR(TAG, "Stream_New failed!");
		return CHANNEL_RC_NO_MEMORY;
	}

	if ((error = rdpgfx_write_header(s, &header)))
		goto fail;

	/* RDPGFX_CAPS_ADVERTISE_PDU */
	Stream_Write_UINT16(s, pdu->capsSetCount); /* capsSetCount (2 bytes) */

	for (UINT16 index = 0; index < pdu->capsSetCount; index++)
	{
		const RDPGFX_CAPSET* capsSet = &(pdu->capsSets[index]);
		Stream_Write_UINT32(s, capsSet->version); /* version (4 bytes) */
		Stream_Write_UINT32(s, capsSet->length);  /* capsDataLength (4 bytes) */
		Stream_Write_UINT32(s, capsSet->flags);   /* capsData (4 bytes) */
		Stream_Zero(s, capsSet->length - 4);
	}

	Stream_SealLength(s);
	error = callback->channel->Write(callback->channel, (UINT32)Stream_Length(s), Stream_Buffer(s),
	                                 NULL);
fail:
	Stream_Free(s, TRUE);
	return error;
}

static BOOL rdpgfx_is_capability_filtered(RDPGFX_PLUGIN* gfx, UINT32 caps)
{
	WINPR_ASSERT(gfx);
	const UINT32 filter =
	    freerdp_settings_get_uint32(gfx->rdpcontext->settings, FreeRDP_GfxCapsFilter);
	const UINT32 capList[] = { RDPGFX_CAPVERSION_8,   RDPGFX_CAPVERSION_81,
		                       RDPGFX_CAPVERSION_10,  RDPGFX_CAPVERSION_101,
		                       RDPGFX_CAPVERSION_102, RDPGFX_CAPVERSION_103,
		                       RDPGFX_CAPVERSION_104, RDPGFX_CAPVERSION_105,
		                       RDPGFX_CAPVERSION_106, RDPGFX_CAPVERSION_106_ERR,
		                       RDPGFX_CAPVERSION_107 };

	for (size_t x = 0; x < ARRAYSIZE(capList); x++)
	{
		if (caps == capList[x])
			return (filter & (1 << x)) != 0;
	}

	return TRUE;
}

/**
 * Function description
 *
 * @return 0 on success, otherwise a Win32 error code
 */
static UINT rdpgfx_send_supported_caps(GENERIC_CHANNEL_CALLBACK* callback)
{
	RDPGFX_PLUGIN* gfx = NULL;
	RdpgfxClientContext* context = NULL;
	RDPGFX_CAPSET* capsSet = NULL;
	RDPGFX_CAPSET capsSets[RDPGFX_NUMBER_CAPSETS] = { 0 };
	RDPGFX_CAPS_ADVERTISE_PDU pdu = { 0 };

	if (!callback)
		return ERROR_BAD_ARGUMENTS;

	gfx = (RDPGFX_PLUGIN*)callback->plugin;

	if (!gfx)
		return ERROR_BAD_CONFIGURATION;

	context = gfx->context;

	if (!context)
		return ERROR_BAD_CONFIGURATION;

	pdu.capsSetCount = 0;
	pdu.capsSets = (RDPGFX_CAPSET*)capsSets;

	if (!rdpgfx_is_capability_filtered(gfx, RDPGFX_CAPVERSION_8))
	{
		capsSet = &capsSets[pdu.capsSetCount++];
		capsSet->version = RDPGFX_CAPVERSION_8;
		capsSet->length = 4;
		capsSet->flags = 0;

		if (freerdp_settings_get_bool(gfx->rdpcontext->settings, FreeRDP_GfxThinClient))
			capsSet->flags |= RDPGFX_CAPS_FLAG_THINCLIENT;

		/* in CAPVERSION_8 the spec says that we should not have both
		 * thinclient and smallcache (and thinclient implies a small cache)
		 */
		if (freerdp_settings_get_bool(gfx->rdpcontext->settings, FreeRDP_GfxSmallCache) &&
		    !freerdp_settings_get_bool(gfx->rdpcontext->settings, FreeRDP_GfxThinClient))
			capsSet->flags |= RDPGFX_CAPS_FLAG_SMALL_CACHE;
	}

	if (!rdpgfx_is_capability_filtered(gfx, RDPGFX_CAPVERSION_81))
	{
		capsSet = &capsSets[pdu.capsSetCount++];
		capsSet->version = RDPGFX_CAPVERSION_81;
		capsSet->length = 4;
		capsSet->flags = 0;

		if (freerdp_settings_get_bool(gfx->rdpcontext->settings, FreeRDP_GfxThinClient))
			capsSet->flags |= RDPGFX_CAPS_FLAG_THINCLIENT;

		if (freerdp_settings_get_bool(gfx->rdpcontext->settings, FreeRDP_GfxSmallCache))
			capsSet->flags |= RDPGFX_CAPS_FLAG_SMALL_CACHE;

#ifdef WITH_GFX_H264

		if (freerdp_settings_get_bool(gfx->rdpcontext->settings, FreeRDP_GfxH264))
			capsSet->flags |= RDPGFX_CAPS_FLAG_AVC420_ENABLED;

#endif
	}

	if (!freerdp_settings_get_bool(gfx->rdpcontext->settings, FreeRDP_GfxH264) ||
	    freerdp_settings_get_bool(gfx->rdpcontext->settings, FreeRDP_GfxAVC444))
	{
		UINT32 caps10Flags = 0;

		if (freerdp_settings_get_bool(gfx->rdpcontext->settings, FreeRDP_GfxSmallCache))
			caps10Flags |= RDPGFX_CAPS_FLAG_SMALL_CACHE;

#ifdef WITH_GFX_H264

		if (!freerdp_settings_get_bool(gfx->rdpcontext->settings, FreeRDP_GfxAVC444))
			caps10Flags |= RDPGFX_CAPS_FLAG_AVC_DISABLED;

#else
		caps10Flags |= RDPGFX_CAPS_FLAG_AVC_DISABLED;
#endif

		if (!rdpgfx_is_capability_filtered(gfx, RDPGFX_CAPVERSION_10))
		{
			capsSet = &capsSets[pdu.capsSetCount++];
			capsSet->version = RDPGFX_CAPVERSION_10;
			capsSet->length = 4;
			capsSet->flags = caps10Flags;
		}

		if (!rdpgfx_is_capability_filtered(gfx, RDPGFX_CAPVERSION_101))
		{
			capsSet = &capsSets[pdu.capsSetCount++];
			capsSet->version = RDPGFX_CAPVERSION_101;
			capsSet->length = 0x10;
			capsSet->flags = 0;
		}

		if (!rdpgfx_is_capability_filtered(gfx, RDPGFX_CAPVERSION_102))
		{
			capsSet = &capsSets[pdu.capsSetCount++];
			capsSet->version = RDPGFX_CAPVERSION_102;
			capsSet->length = 0x4;
			capsSet->flags = caps10Flags;
		}

		if (freerdp_settings_get_bool(gfx->rdpcontext->settings, FreeRDP_GfxThinClient))
		{
			if ((caps10Flags & RDPGFX_CAPS_FLAG_AVC_DISABLED) == 0)
				caps10Flags |= RDPGFX_CAPS_FLAG_AVC_THINCLIENT;
		}

		if (!rdpgfx_is_capability_filtered(gfx, RDPGFX_CAPVERSION_103))
		{
			capsSet = &capsSets[pdu.capsSetCount++];
			capsSet->version = RDPGFX_CAPVERSION_103;
			capsSet->length = 0x4;
			capsSet->flags = caps10Flags & ~RDPGFX_CAPS_FLAG_SMALL_CACHE;
		}

		if (!rdpgfx_is_capability_filtered(gfx, RDPGFX_CAPVERSION_104))
		{
			capsSet = &capsSets[pdu.capsSetCount++];
			capsSet->version = RDPGFX_CAPVERSION_104;
			capsSet->length = 0x4;
			capsSet->flags = caps10Flags;
		}

		/* The following capabilities expect support for image scaling.
		 * Disable these for builds that do not have support for that.
		 */
#if defined(WITH_CAIRO) || defined(WITH_SWSCALE)
		if (!rdpgfx_is_capability_filtered(gfx, RDPGFX_CAPVERSION_105))
		{
			capsSet = &capsSets[pdu.capsSetCount++];
			capsSet->version = RDPGFX_CAPVERSION_105;
			capsSet->length = 0x4;
			capsSet->flags = caps10Flags;
		}

		if (!rdpgfx_is_capability_filtered(gfx, RDPGFX_CAPVERSION_106))
		{
			capsSet = &capsSets[pdu.capsSetCount++];
			capsSet->version = RDPGFX_CAPVERSION_106;
			capsSet->length = 0x4;
			capsSet->flags = caps10Flags;
		}

		if (!rdpgfx_is_capability_filtered(gfx, RDPGFX_CAPVERSION_106_ERR))
		{
			capsSet = &capsSets[pdu.capsSetCount++];
			capsSet->version = RDPGFX_CAPVERSION_106_ERR;
			capsSet->length = 0x4;
			capsSet->flags = caps10Flags;
		}
#endif

		if (!rdpgfx_is_capability_filtered(gfx, RDPGFX_CAPVERSION_107))
		{
			capsSet = &capsSets[pdu.capsSetCount++];
			capsSet->version = RDPGFX_CAPVERSION_107;
			capsSet->length = 0x4;
			capsSet->flags = caps10Flags;
#if !defined(WITH_CAIRO) && !defined(WITH_SWSCALE)
			capsSet->flags |= RDPGFX_CAPS_FLAG_SCALEDMAP_DISABLE;
#endif
		}
	}

	return IFCALLRESULT(ERROR_BAD_CONFIGURATION, context->CapsAdvertise, context, &pdu);
}

/**
 * Function description
 *
 * @return 0 on success, otherwise a Win32 error code
 */
static UINT rdpgfx_recv_caps_confirm_pdu(GENERIC_CHANNEL_CALLBACK* callback, wStream* s)
{
	RDPGFX_CAPSET capsSet = { 0 };
	RDPGFX_CAPS_CONFIRM_PDU pdu = { 0 };
	WINPR_ASSERT(callback);
	RDPGFX_PLUGIN* gfx = (RDPGFX_PLUGIN*)callback->plugin;

	WINPR_ASSERT(gfx);
	RdpgfxClientContext* context = gfx->context;

	pdu.capsSet = &capsSet;

	if (!Stream_CheckAndLogRequiredLength(TAG, s, 12))
		return ERROR_INVALID_DATA;

	Stream_Read_UINT32(s, capsSet.version); /* version (4 bytes) */
	Stream_Read_UINT32(s, capsSet.length);  /* capsDataLength (4 bytes) */
	Stream_Read_UINT32(s, capsSet.flags);   /* capsData (4 bytes) */
	gfx->TotalDecodedFrames = 0;
	gfx->ConnectionCaps = capsSet;
	DEBUG_RDPGFX(gfx->log, "RecvCapsConfirmPdu: version: 0x%08" PRIX32 " flags: 0x%08" PRIX32 "",
	             capsSet.version, capsSet.flags);

	if (!context)
		return ERROR_BAD_CONFIGURATION;

	return IFCALLRESULT(CHANNEL_RC_OK, context->CapsConfirm, context, &pdu);
}

/**
 * Function description
 *
 * @return 0 on success, otherwise a Win32 error code
 */
static UINT rdpgfx_send_frame_acknowledge_pdu(RdpgfxClientContext* context,
                                              const RDPGFX_FRAME_ACKNOWLEDGE_PDU* pdu)
{
	UINT error = 0;
	wStream* s = NULL;
	RDPGFX_HEADER header = { 0 };
	RDPGFX_PLUGIN* gfx = NULL;
	GENERIC_CHANNEL_CALLBACK* callback = NULL;

	if (!context || !pdu)
		return ERROR_BAD_ARGUMENTS;

	gfx = (RDPGFX_PLUGIN*)context->handle;

	if (!gfx || !gfx->base.listener_callback)
		return ERROR_BAD_CONFIGURATION;

	callback = gfx->base.listener_callback->channel_callback;

	if (!callback)
		return ERROR_BAD_CONFIGURATION;

	header.flags = 0;
	header.cmdId = RDPGFX_CMDID_FRAMEACKNOWLEDGE;
	header.pduLength = RDPGFX_HEADER_SIZE + 12;
	DEBUG_RDPGFX(gfx->log, "SendFrameAcknowledgePdu: %" PRIu32 "", pdu->frameId);
	s = Stream_New(NULL, header.pduLength);

	if (!s)
	{
		WLog_ERR(TAG, "Stream_New failed!");
		return CHANNEL_RC_NO_MEMORY;
	}

	if ((error = rdpgfx_write_header(s, &header)))
		goto fail;

	/* RDPGFX_FRAME_ACKNOWLEDGE_PDU */
	Stream_Write_UINT32(s, pdu->queueDepth);         /* queueDepth (4 bytes) */
	Stream_Write_UINT32(s, pdu->frameId);            /* frameId (4 bytes) */
	Stream_Write_UINT32(s, pdu->totalFramesDecoded); /* totalFramesDecoded (4 bytes) */
	error = callback->channel->Write(callback->channel, (UINT32)Stream_Length(s), Stream_Buffer(s),
	                                 NULL);

	if (error == CHANNEL_RC_OK) /* frame successfully acked */
		gfx->UnacknowledgedFrames--;

fail:
	Stream_Free(s, TRUE);
	return error;
}

static UINT rdpgfx_send_qoe_frame_acknowledge_pdu(RdpgfxClientContext* context,
                                                  const RDPGFX_QOE_FRAME_ACKNOWLEDGE_PDU* pdu)
{
	UINT error = 0;
	wStream* s = NULL;
	RDPGFX_HEADER header = { 0 };
	GENERIC_CHANNEL_CALLBACK* callback = NULL;
	RDPGFX_PLUGIN* gfx = NULL;

	header.flags = 0;
	header.cmdId = RDPGFX_CMDID_QOEFRAMEACKNOWLEDGE;
	header.pduLength = RDPGFX_HEADER_SIZE + 12;

	if (!context || !pdu)
		return ERROR_BAD_ARGUMENTS;

	gfx = (RDPGFX_PLUGIN*)context->handle;

	if (!gfx || !gfx->base.listener_callback)
		return ERROR_BAD_CONFIGURATION;

	callback = gfx->base.listener_callback->channel_callback;

	if (!callback)
		return ERROR_BAD_CONFIGURATION;

	DEBUG_RDPGFX(gfx->log, "SendQoeFrameAcknowledgePdu: %" PRIu32 "", pdu->frameId);
	s = Stream_New(NULL, header.pduLength);

	if (!s)
	{
		WLog_ERR(TAG, "Stream_New failed!");
		return CHANNEL_RC_NO_MEMORY;
	}

	if ((error = rdpgfx_write_header(s, &header)))
		goto fail;

	/* RDPGFX_FRAME_ACKNOWLEDGE_PDU */
	Stream_Write_UINT32(s, pdu->frameId);
	Stream_Write_UINT32(s, pdu->timestamp);
	Stream_Write_UINT16(s, pdu->timeDiffSE);
	Stream_Write_UINT16(s, pdu->timeDiffEDR);
	error = callback->channel->Write(callback->channel, (UINT32)Stream_Length(s), Stream_Buffer(s),
	                                 NULL);
fail:
	Stream_Free(s, TRUE);
	return error;
}

/**
 * Function description
 *
 * @return 0 on success, otherwise a Win32 error code
 */
static UINT rdpgfx_recv_reset_graphics_pdu(GENERIC_CHANNEL_CALLBACK* callback, wStream* s)
{
	int pad = 0;
	MONITOR_DEF* monitor = NULL;
	RDPGFX_RESET_GRAPHICS_PDU pdu = { 0 };
	WINPR_ASSERT(callback);

	RDPGFX_PLUGIN* gfx = (RDPGFX_PLUGIN*)callback->plugin;

	WINPR_ASSERT(gfx);

	RdpgfxClientContext* context = gfx->context;
	UINT error = CHANNEL_RC_OK;
	GraphicsResetEventArgs graphicsReset = { 0 };

	if (!Stream_CheckAndLogRequiredLength(TAG, s, 12))
		return ERROR_INVALID_DATA;

	Stream_Read_UINT32(s, pdu.width);        /* width (4 bytes) */
	Stream_Read_UINT32(s, pdu.height);       /* height (4 bytes) */
	Stream_Read_UINT32(s, pdu.monitorCount); /* monitorCount (4 bytes) */

	if (!Stream_CheckAndLogRequiredLengthOfSize(TAG, s, pdu.monitorCount, 20ull))
		return ERROR_INVALID_DATA;

	pdu.monitorDefArray = (MONITOR_DEF*)calloc(pdu.monitorCount, sizeof(MONITOR_DEF));

	if (!pdu.monitorDefArray)
	{
		WLog_Print(gfx->log, WLOG_ERROR, "calloc failed!");
		return CHANNEL_RC_NO_MEMORY;
	}

	for (UINT32 index = 0; index < pdu.monitorCount; index++)
	{
		monitor = &(pdu.monitorDefArray[index]);
		Stream_Read_INT32(s, monitor->left);   /* left (4 bytes) */
		Stream_Read_INT32(s, monitor->top);    /* top (4 bytes) */
		Stream_Read_INT32(s, monitor->right);  /* right (4 bytes) */
		Stream_Read_INT32(s, monitor->bottom); /* bottom (4 bytes) */
		Stream_Read_UINT32(s, monitor->flags); /* flags (4 bytes) */
	}

	pad = 340 - (RDPGFX_HEADER_SIZE + 12 + (pdu.monitorCount * 20));

	if (!Stream_CheckAndLogRequiredLength(TAG, s, (size_t)pad))
	{
		free(pdu.monitorDefArray);
		return CHANNEL_RC_NO_MEMORY;
	}

	Stream_Seek(s, pad); /* pad (total size is 340 bytes) */
	DEBUG_RDPGFX(gfx->log,
	             "RecvResetGraphicsPdu: width: %" PRIu32 " height: %" PRIu32 " count: %" PRIu32 "",
	             pdu.width, pdu.height, pdu.monitorCount);

#if defined(WITH_DEBUG_RDPGFX)
	for (UINT32 index = 0; index < pdu.monitorCount; index++)
	{
		monitor = &(pdu.monitorDefArray[index]);
		DEBUG_RDPGFX(gfx->log,
		             "RecvResetGraphicsPdu: monitor left:%" PRIi32 " top:%" PRIi32 " right:%" PRIi32
		             " bottom:%" PRIi32 " flags:0x%" PRIx32 "",
		             monitor->left, monitor->top, monitor->right, monitor->bottom, monitor->flags);
	}
#endif

	if (context)
	{
		IFCALLRET(context->ResetGraphics, error, context, &pdu);

		if (error)
			WLog_Print(gfx->log, WLOG_ERROR, "context->ResetGraphics failed with error %" PRIu32 "",
			           error);
	}

	/* some listeners may be interested (namely the display channel) */
	EventArgsInit(&graphicsReset, "libfreerdp");
	graphicsReset.width = pdu.width;
	graphicsReset.height = pdu.height;
	PubSub_OnGraphicsReset(gfx->rdpcontext->pubSub, gfx->rdpcontext, &graphicsReset);
	free(pdu.monitorDefArray);
	return error;
}

/**
 * Function description
 *
 * @return 0 on success, otherwise a Win32 error code
 */
static UINT rdpgfx_recv_evict_cache_entry_pdu(GENERIC_CHANNEL_CALLBACK* callback, wStream* s)
{
	RDPGFX_EVICT_CACHE_ENTRY_PDU pdu = { 0 };
	WINPR_ASSERT(callback);
	RDPGFX_PLUGIN* gfx = (RDPGFX_PLUGIN*)callback->plugin;
	WINPR_ASSERT(gfx);
	RdpgfxClientContext* context = gfx->context;
	UINT error = CHANNEL_RC_OK;

	if (!Stream_CheckAndLogRequiredLength(TAG, s, 2))
		return ERROR_INVALID_DATA;

	Stream_Read_UINT16(s, pdu.cacheSlot); /* cacheSlot (2 bytes) */
	WLog_Print(gfx->log, WLOG_DEBUG, "RecvEvictCacheEntryPdu: cacheSlot: %" PRIu16 "",
	           pdu.cacheSlot);

	if (context)
	{
		IFCALLRET(context->EvictCacheEntry, error, context, &pdu);

		if (error)
			WLog_Print(gfx->log, WLOG_ERROR,
			           "context->EvictCacheEntry failed with error %" PRIu32 "", error);
	}

	return error;
}

/**
 * Load cache import offer from file (offline replay)
 *
 * @return 0 on success, otherwise a Win32 error code
 */
static UINT rdpgfx_load_cache_import_offer(RDPGFX_PLUGIN* gfx, RDPGFX_CACHE_IMPORT_OFFER_PDU* offer)
{
	int count = 0;
	UINT error = CHANNEL_RC_OK;
	PERSISTENT_CACHE_ENTRY entry;
	rdpPersistentCache* persistent = NULL;
	WINPR_ASSERT(gfx);
	WINPR_ASSERT(gfx->rdpcontext);
	rdpSettings* settings = gfx->rdpcontext->settings;

	WINPR_ASSERT(offer);
	WINPR_ASSERT(settings);

	offer->cacheEntriesCount = 0;

	if (!freerdp_settings_get_bool(settings, FreeRDP_BitmapCachePersistEnabled))
		return CHANNEL_RC_OK;

	const char* BitmapCachePersistFile =
	    freerdp_settings_get_string(settings, FreeRDP_BitmapCachePersistFile);
	if (!BitmapCachePersistFile)
		return CHANNEL_RC_OK;

	persistent = persistent_cache_new();

	if (!persistent)
		return CHANNEL_RC_NO_MEMORY;

	if (persistent_cache_open(persistent, BitmapCachePersistFile, FALSE, 3) < 1)
	{
		error = CHANNEL_RC_INITIALIZATION_ERROR;
		goto fail;
	}

	if (persistent_cache_get_version(persistent) != 3)
	{
		error = ERROR_INVALID_DATA;
		goto fail;
	}

	count = persistent_cache_get_count(persistent);

	if (count < 1)
	{
		error = ERROR_INVALID_DATA;
		goto fail;
	}

	if (count >= RDPGFX_CACHE_ENTRY_MAX_COUNT)
		count = RDPGFX_CACHE_ENTRY_MAX_COUNT - 1;

	if (count > gfx->MaxCacheSlots)
		count = gfx->MaxCacheSlots;

	offer->cacheEntriesCount = (UINT16)count;

	for (int idx = 0; idx < count; idx++)
	{
		if (persistent_cache_read_entry(persistent, &entry) < 1)
		{
			error = ERROR_INVALID_DATA;
			goto fail;
		}

		offer->cacheEntries[idx].cacheKey = entry.key64;
		offer->cacheEntries[idx].bitmapLength = entry.size;
	}

	persistent_cache_free(persistent);

	return error;
fail:
	persistent_cache_free(persistent);
	return error;
}

/**
 * Function description
 *
 * @return 0 on success, otherwise a Win32 error code
 */
static UINT rdpgfx_save_persistent_cache(RDPGFX_PLUGIN* gfx)
{
	UINT error = CHANNEL_RC_OK;
	PERSISTENT_CACHE_ENTRY cacheEntry;
	rdpPersistentCache* persistent = NULL;
	WINPR_ASSERT(gfx);
	WINPR_ASSERT(gfx->rdpcontext);
	rdpSettings* settings = gfx->rdpcontext->settings;
	RdpgfxClientContext* context = gfx->context;

	WINPR_ASSERT(context);
	WINPR_ASSERT(settings);

	if (!freerdp_settings_get_bool(settings, FreeRDP_BitmapCachePersistEnabled))
		return CHANNEL_RC_OK;

	const char* BitmapCachePersistFile =
	    freerdp_settings_get_string(settings, FreeRDP_BitmapCachePersistFile);
	if (!BitmapCachePersistFile)
		return CHANNEL_RC_OK;

	if (!context->ExportCacheEntry)
		return CHANNEL_RC_INITIALIZATION_ERROR;

	persistent = persistent_cache_new();

	if (!persistent)
		return CHANNEL_RC_NO_MEMORY;

	if (persistent_cache_open(persistent, BitmapCachePersistFile, TRUE, 3) < 1)
	{
		error = CHANNEL_RC_INITIALIZATION_ERROR;
		goto fail;
	}

	for (UINT16 idx = 0; idx < gfx->MaxCacheSlots; idx++)
	{
		if (gfx->CacheSlots[idx])
		{
			UINT16 cacheSlot = (UINT16)idx;

			if (context->ExportCacheEntry(context, cacheSlot, &cacheEntry) != CHANNEL_RC_OK)
				continue;

			persistent_cache_write_entry(persistent, &cacheEntry);
		}
	}

	persistent_cache_free(persistent);

	return error;
fail:
	persistent_cache_free(persistent);
	return error;
}

/**
 * Function description
 *
 * @return 0 on success, otherwise a Win32 error code
 */
static UINT rdpgfx_send_cache_import_offer_pdu(RdpgfxClientContext* context,
                                               const RDPGFX_CACHE_IMPORT_OFFER_PDU* pdu)
{
	UINT error = CHANNEL_RC_OK;
	wStream* s = NULL;
	RDPGFX_HEADER header;
	GENERIC_CHANNEL_CALLBACK* callback = NULL;
	WINPR_ASSERT(context);
	RDPGFX_PLUGIN* gfx = (RDPGFX_PLUGIN*)context->handle;

	if (!context || !pdu)
		return ERROR_BAD_ARGUMENTS;

	gfx = (RDPGFX_PLUGIN*)context->handle;

	if (!gfx || !gfx->base.listener_callback)
		return ERROR_BAD_CONFIGURATION;

	callback = gfx->base.listener_callback->channel_callback;

	if (!callback)
		return ERROR_BAD_CONFIGURATION;

	header.flags = 0;
	header.cmdId = RDPGFX_CMDID_CACHEIMPORTOFFER;
	header.pduLength = RDPGFX_HEADER_SIZE + 2 + pdu->cacheEntriesCount * 12;
	DEBUG_RDPGFX(gfx->log, "SendCacheImportOfferPdu: cacheEntriesCount: %" PRIu16 "",
	             pdu->cacheEntriesCount);
	s = Stream_New(NULL, header.pduLength);

	if (!s)
	{
		WLog_ERR(TAG, "Stream_New failed!");
		return CHANNEL_RC_NO_MEMORY;
	}

	if ((error = rdpgfx_write_header(s, &header)))
		goto fail;

	if (pdu->cacheEntriesCount <= 0)
	{
		WLog_ERR(TAG, "Invalid cacheEntriesCount: %" PRIu16 "", pdu->cacheEntriesCount);
		error = ERROR_INVALID_DATA;
		goto fail;
	}

	/* cacheEntriesCount (2 bytes) */
	Stream_Write_UINT16(s, pdu->cacheEntriesCount);

	for (UINT16 index = 0; index < pdu->cacheEntriesCount; index++)
	{
		const RDPGFX_CACHE_ENTRY_METADATA* cacheEntry = &(pdu->cacheEntries[index]);
		Stream_Write_UINT64(s, cacheEntry->cacheKey);     /* cacheKey (8 bytes) */
		Stream_Write_UINT32(s, cacheEntry->bitmapLength); /* bitmapLength (4 bytes) */
	}

	error = callback->channel->Write(callback->channel, (UINT32)Stream_Length(s), Stream_Buffer(s),
	                                 NULL);

fail:
	Stream_Free(s, TRUE);
	return error;
}

/**
 * Function description
 *
 * @return 0 on success, otherwise a Win32 error code
 */
static UINT rdpgfx_send_cache_offer(RDPGFX_PLUGIN* gfx)
{
	int count = 0;
	UINT error = CHANNEL_RC_OK;
	PERSISTENT_CACHE_ENTRY entry;
	RDPGFX_CACHE_IMPORT_OFFER_PDU* offer = NULL;
	rdpPersistentCache* persistent = NULL;

	WINPR_ASSERT(gfx);
	WINPR_ASSERT(gfx->rdpcontext);

	RdpgfxClientContext* context = gfx->context;
	rdpSettings* settings = gfx->rdpcontext->settings;

	if (!freerdp_settings_get_bool(settings, FreeRDP_BitmapCachePersistEnabled))
		return CHANNEL_RC_OK;

	const char* BitmapCachePersistFile =
	    freerdp_settings_get_string(settings, FreeRDP_BitmapCachePersistFile);
	if (!BitmapCachePersistFile)
		return CHANNEL_RC_OK;

	persistent = persistent_cache_new();

	if (!persistent)
		return CHANNEL_RC_NO_MEMORY;

	if (persistent_cache_open(persistent, BitmapCachePersistFile, FALSE, 3) < 1)
	{
		error = CHANNEL_RC_INITIALIZATION_ERROR;
		goto fail;
	}

	if (persistent_cache_get_version(persistent) != 3)
	{
		error = ERROR_INVALID_DATA;
		goto fail;
	}

	count = persistent_cache_get_count(persistent);

	if (count >= RDPGFX_CACHE_ENTRY_MAX_COUNT)
		count = RDPGFX_CACHE_ENTRY_MAX_COUNT - 1;

	if (count > gfx->MaxCacheSlots)
		count = gfx->MaxCacheSlots;

	offer = (RDPGFX_CACHE_IMPORT_OFFER_PDU*)calloc(1, sizeof(RDPGFX_CACHE_IMPORT_OFFER_PDU));
	if (!offer)
	{
		error = CHANNEL_RC_NO_MEMORY;
		goto fail;
	}

	offer->cacheEntriesCount = (UINT16)count;

	WLog_DBG(TAG, "Sending Cache Import Offer: %d", count);

	for (int idx = 0; idx < count; idx++)
	{
		if (persistent_cache_read_entry(persistent, &entry) < 1)
		{
			error = ERROR_INVALID_DATA;
			goto fail;
		}

		offer->cacheEntries[idx].cacheKey = entry.key64;
		offer->cacheEntries[idx].bitmapLength = entry.size;
	}

	if (offer->cacheEntriesCount > 0)
	{
		error = rdpgfx_send_cache_import_offer_pdu(context, offer);
		if (error != CHANNEL_RC_OK)
		{
			WLog_Print(gfx->log, WLOG_ERROR, "Failed to send cache import offer PDU");
			goto fail;
		}
	}

fail:
	persistent_cache_free(persistent);
	free(offer);
	return error;
}

/**
 * Function description
 *
 * @return 0 on success, otherwise a Win32 error code
 */
static UINT rdpgfx_load_cache_import_reply(RDPGFX_PLUGIN* gfx,
                                           const RDPGFX_CACHE_IMPORT_REPLY_PDU* reply)
{
	int count = 0;
	UINT error = CHANNEL_RC_OK;
	rdpPersistentCache* persistent = NULL;
	WINPR_ASSERT(gfx);
	WINPR_ASSERT(gfx->rdpcontext);
	rdpSettings* settings = gfx->rdpcontext->settings;
	RdpgfxClientContext* context = gfx->context;

	WINPR_ASSERT(settings);
	WINPR_ASSERT(reply);
	if (!freerdp_settings_get_bool(settings, FreeRDP_BitmapCachePersistEnabled))
		return CHANNEL_RC_OK;

	const char* BitmapCachePersistFile =
	    freerdp_settings_get_string(settings, FreeRDP_BitmapCachePersistFile);
	if (!BitmapCachePersistFile)
		return CHANNEL_RC_OK;

	persistent = persistent_cache_new();

	if (!persistent)
		return CHANNEL_RC_NO_MEMORY;

	if (persistent_cache_open(persistent, BitmapCachePersistFile, FALSE, 3) < 1)
	{
		error = CHANNEL_RC_INITIALIZATION_ERROR;
		goto fail;
	}

	if (persistent_cache_get_version(persistent) != 3)
	{
		error = ERROR_INVALID_DATA;
		goto fail;
	}

	count = persistent_cache_get_count(persistent);

	count = (count < reply->importedEntriesCount) ? count : reply->importedEntriesCount;

	WLog_DBG(TAG, "Receiving Cache Import Reply: %d", count);

	for (int idx = 0; idx < count; idx++)
	{
		PERSISTENT_CACHE_ENTRY entry = { 0 };
		if (persistent_cache_read_entry(persistent, &entry) < 1)
		{
			error = ERROR_INVALID_DATA;
			goto fail;
		}

		const UINT16 cacheSlot = reply->cacheSlots[idx];
		if (context && context->ImportCacheEntry)
			context->ImportCacheEntry(context, cacheSlot, &entry);
	}

	persistent_cache_free(persistent);

	return error;
fail:
	persistent_cache_free(persistent);
	return error;
}

/**
 * Function description
 *
 * @return 0 on success, otherwise a Win32 error code
 */
static UINT rdpgfx_recv_cache_import_reply_pdu(GENERIC_CHANNEL_CALLBACK* callback, wStream* s)
{
	RDPGFX_CACHE_IMPORT_REPLY_PDU pdu = { 0 };
	WINPR_ASSERT(callback);
	RDPGFX_PLUGIN* gfx = (RDPGFX_PLUGIN*)callback->plugin;
	WINPR_ASSERT(gfx);
	RdpgfxClientContext* context = gfx->context;
	UINT error = CHANNEL_RC_OK;

	if (!Stream_CheckAndLogRequiredLength(TAG, s, 2))
		return ERROR_INVALID_DATA;

	Stream_Read_UINT16(s, pdu.importedEntriesCount); /* cacheSlot (2 bytes) */

	if (!Stream_CheckAndLogRequiredLengthOfSize(TAG, s, pdu.importedEntriesCount, 2ull))
		return ERROR_INVALID_DATA;

	if (pdu.importedEntriesCount > RDPGFX_CACHE_ENTRY_MAX_COUNT)
		return ERROR_INVALID_DATA;

	for (UINT16 idx = 0; idx < pdu.importedEntriesCount; idx++)
	{
		Stream_Read_UINT16(s, pdu.cacheSlots[idx]); /* cacheSlot (2 bytes) */
	}

	DEBUG_RDPGFX(gfx->log, "RecvCacheImportReplyPdu: importedEntriesCount: %" PRIu16 "",
	             pdu.importedEntriesCount);

	error = rdpgfx_load_cache_import_reply(gfx, &pdu);

	if (error)
	{
		WLog_Print(gfx->log, WLOG_ERROR,
		           "rdpgfx_load_cache_import_reply failed with error %" PRIu32 "", error);
		return error;
	}

	if (context)
	{
		IFCALLRET(context->CacheImportReply, error, context, &pdu);

		if (error)
			WLog_Print(gfx->log, WLOG_ERROR,
			           "context->CacheImportReply failed with error %" PRIu32 "", error);
	}

	return error;
}

/**
 * Function description
 *
 * @return 0 on success, otherwise a Win32 error code
 */
static UINT rdpgfx_recv_create_surface_pdu(GENERIC_CHANNEL_CALLBACK* callback, wStream* s)
{
	RDPGFX_CREATE_SURFACE_PDU pdu = { 0 };
	WINPR_ASSERT(callback);
	RDPGFX_PLUGIN* gfx = (RDPGFX_PLUGIN*)callback->plugin;
	WINPR_ASSERT(gfx);
	RdpgfxClientContext* context = gfx->context;
	UINT error = CHANNEL_RC_OK;

	if (!Stream_CheckAndLogRequiredLength(TAG, s, 7))
		return ERROR_INVALID_DATA;

	Stream_Read_UINT16(s, pdu.surfaceId);  /* surfaceId (2 bytes) */
	Stream_Read_UINT16(s, pdu.width);      /* width (2 bytes) */
	Stream_Read_UINT16(s, pdu.height);     /* height (2 bytes) */
	Stream_Read_UINT8(s, pdu.pixelFormat); /* RDPGFX_PIXELFORMAT (1 byte) */
	DEBUG_RDPGFX(gfx->log,
	             "RecvCreateSurfacePdu: surfaceId: %" PRIu16 " width: %" PRIu16 " height: %" PRIu16
	             " pixelFormat: 0x%02" PRIX8 "",
	             pdu.surfaceId, pdu.width, pdu.height, pdu.pixelFormat);

	if (context)
	{
		/* create surface PDU sometimes happens for surface ID that are already in use and have not
		 * been removed yet. Ensure that there is no surface with the new ID by trying to remove it
		 * manually.
		 */
		RDPGFX_DELETE_SURFACE_PDU deletePdu = { pdu.surfaceId };
		IFCALL(context->DeleteSurface, context, &deletePdu);

		IFCALLRET(context->CreateSurface, error, context, &pdu);

		if (error)
			WLog_Print(gfx->log, WLOG_ERROR, "context->CreateSurface failed with error %" PRIu32 "",
			           error);
	}

	return error;
}

/**
 * Function description
 *
 * @return 0 on success, otherwise a Win32 error code
 */
static UINT rdpgfx_recv_delete_surface_pdu(GENERIC_CHANNEL_CALLBACK* callback, wStream* s)
{
	RDPGFX_DELETE_SURFACE_PDU pdu = { 0 };
	WINPR_ASSERT(callback);
	RDPGFX_PLUGIN* gfx = (RDPGFX_PLUGIN*)callback->plugin;
	WINPR_ASSERT(gfx);
	RdpgfxClientContext* context = gfx->context;
	UINT error = CHANNEL_RC_OK;

	if (!Stream_CheckAndLogRequiredLength(TAG, s, 2))
		return ERROR_INVALID_DATA;

	Stream_Read_UINT16(s, pdu.surfaceId); /* surfaceId (2 bytes) */
	DEBUG_RDPGFX(gfx->log, "RecvDeleteSurfacePdu: surfaceId: %" PRIu16 "", pdu.surfaceId);

	if (context)
	{
		IFCALLRET(context->DeleteSurface, error, context, &pdu);

		if (error)
			WLog_Print(gfx->log, WLOG_ERROR, "context->DeleteSurface failed with error %" PRIu32 "",
			           error);
	}

	return error;
}

/**
 * Function description
 *
 * @return 0 on success, otherwise a Win32 error code
 */
static UINT rdpgfx_recv_start_frame_pdu(GENERIC_CHANNEL_CALLBACK* callback, wStream* s)
{
	RDPGFX_START_FRAME_PDU pdu = { 0 };
	WINPR_ASSERT(callback);
	RDPGFX_PLUGIN* gfx = (RDPGFX_PLUGIN*)callback->plugin;
	WINPR_ASSERT(gfx);
	RdpgfxClientContext* context = gfx->context;
	UINT error = CHANNEL_RC_OK;

	if (!Stream_CheckAndLogRequiredLength(TAG, s, RDPGFX_START_FRAME_PDU_SIZE))
		return ERROR_INVALID_DATA;

	Stream_Read_UINT32(s, pdu.timestamp); /* timestamp (4 bytes) */
	Stream_Read_UINT32(s, pdu.frameId);   /* frameId (4 bytes) */
	DEBUG_RDPGFX(gfx->log, "RecvStartFramePdu: frameId: %" PRIu32 " timestamp: 0x%08" PRIX32 "",
	             pdu.frameId, pdu.timestamp);
	gfx->StartDecodingTime = GetTickCount64();

	if (context)
	{
		IFCALLRET(context->StartFrame, error, context, &pdu);

		if (error)
			WLog_Print(gfx->log, WLOG_ERROR, "context->StartFrame failed with error %" PRIu32 "",
			           error);
	}

	gfx->UnacknowledgedFrames++;
	return error;
}

/**
 * Function description
 *
 * @return 0 on success, otherwise a Win32 error code
 */
static UINT rdpgfx_recv_end_frame_pdu(GENERIC_CHANNEL_CALLBACK* callback, wStream* s)
{
	RDPGFX_END_FRAME_PDU pdu = { 0 };
	RDPGFX_FRAME_ACKNOWLEDGE_PDU ack = { 0 };
	WINPR_ASSERT(callback);
	RDPGFX_PLUGIN* gfx = (RDPGFX_PLUGIN*)callback->plugin;
	WINPR_ASSERT(gfx);
	RdpgfxClientContext* context = gfx->context;
	UINT error = CHANNEL_RC_OK;

	if (!Stream_CheckAndLogRequiredLength(TAG, s, RDPGFX_END_FRAME_PDU_SIZE))
		return ERROR_INVALID_DATA;

	Stream_Read_UINT32(s, pdu.frameId); /* frameId (4 bytes) */
	DEBUG_RDPGFX(gfx->log, "RecvEndFramePdu: frameId: %" PRIu32 "", pdu.frameId);

	if (context)
	{
		IFCALLRET(context->EndFrame, error, context, &pdu);

		if (error)
		{
			WLog_Print(gfx->log, WLOG_ERROR, "context->EndFrame failed with error %" PRIu32 "",
			           error);
			return error;
		}
	}

	gfx->TotalDecodedFrames++;

	if (!gfx->sendFrameAcks)
		return error;

	ack.frameId = pdu.frameId;
	ack.totalFramesDecoded = gfx->TotalDecodedFrames;

	if (gfx->suspendFrameAcks)
	{
		ack.queueDepth = SUSPEND_FRAME_ACKNOWLEDGEMENT;

		if (gfx->TotalDecodedFrames == 1)
			if ((error = rdpgfx_send_frame_acknowledge_pdu(context, &ack)))
				WLog_Print(gfx->log, WLOG_ERROR,
				           "rdpgfx_send_frame_acknowledge_pdu failed with error %" PRIu32 "",
				           error);
	}
	else
	{
		ack.queueDepth = QUEUE_DEPTH_UNAVAILABLE;

		if ((error = rdpgfx_send_frame_acknowledge_pdu(context, &ack)))
			WLog_Print(gfx->log, WLOG_ERROR,
			           "rdpgfx_send_frame_acknowledge_pdu failed with error %" PRIu32 "", error);
	}

	switch (gfx->ConnectionCaps.version)
	{
		case RDPGFX_CAPVERSION_10:
		case RDPGFX_CAPVERSION_102:
		case RDPGFX_CAPVERSION_103:
		case RDPGFX_CAPVERSION_104:
		case RDPGFX_CAPVERSION_105:
		case RDPGFX_CAPVERSION_106:
		case RDPGFX_CAPVERSION_106_ERR:
		case RDPGFX_CAPVERSION_107:
			if (freerdp_settings_get_bool(gfx->rdpcontext->settings, FreeRDP_GfxSendQoeAck))
			{
				RDPGFX_QOE_FRAME_ACKNOWLEDGE_PDU qoe;
				UINT64 diff = (GetTickCount64() - gfx->StartDecodingTime);

				if (diff > 65000)
					diff = 0;

				qoe.frameId = pdu.frameId;
				qoe.timestamp = gfx->StartDecodingTime;
				qoe.timeDiffSE = diff;
				qoe.timeDiffEDR = 1;

				if ((error = rdpgfx_send_qoe_frame_acknowledge_pdu(context, &qoe)))
					WLog_Print(gfx->log, WLOG_ERROR,
					           "rdpgfx_send_qoe_frame_acknowledge_pdu failed with error %" PRIu32
					           "",
					           error);
			}

			break;

		default:
			break;
	}

	return error;
}

/**
 * Function description
 *
 * @return 0 on success, otherwise a Win32 error code
 */
static UINT rdpgfx_recv_wire_to_surface_1_pdu(GENERIC_CHANNEL_CALLBACK* callback, wStream* s)
{
	RDPGFX_SURFACE_COMMAND cmd = { 0 };
	RDPGFX_WIRE_TO_SURFACE_PDU_1 pdu = { 0 };
	WINPR_ASSERT(callback);
	RDPGFX_PLUGIN* gfx = (RDPGFX_PLUGIN*)callback->plugin;
	UINT error = 0;

	WINPR_ASSERT(gfx);
	if (!Stream_CheckAndLogRequiredLength(TAG, s, RDPGFX_WIRE_TO_SURFACE_PDU_1_SIZE))
		return ERROR_INVALID_DATA;

	Stream_Read_UINT16(s, pdu.surfaceId);  /* surfaceId (2 bytes) */
	Stream_Read_UINT16(s, pdu.codecId);    /* codecId (2 bytes) */
	Stream_Read_UINT8(s, pdu.pixelFormat); /* pixelFormat (1 byte) */

	if ((error = rdpgfx_read_rect16(s, &(pdu.destRect)))) /* destRect (8 bytes) */
	{
		WLog_Print(gfx->log, WLOG_ERROR, "rdpgfx_read_rect16 failed with error %" PRIu32 "", error);
		return error;
	}

	Stream_Read_UINT32(s, pdu.bitmapDataLength); /* bitmapDataLength (4 bytes) */

	if (!Stream_CheckAndLogRequiredLength(TAG, s, pdu.bitmapDataLength))
		return ERROR_INVALID_DATA;

	pdu.bitmapData = Stream_Pointer(s);
	Stream_Seek(s, pdu.bitmapDataLength);

	DEBUG_RDPGFX(gfx->log,
	             "RecvWireToSurface1Pdu: surfaceId: %" PRIu16 " codecId: %s (0x%04" PRIX16
	             ") pixelFormat: 0x%02" PRIX8 " "
	             "destRect: left: %" PRIu16 " top: %" PRIu16 " right: %" PRIu16 " bottom: %" PRIu16
	             " bitmapDataLength: %" PRIu32 "",
	             pdu.surfaceId, rdpgfx_get_codec_id_string(pdu.codecId), pdu.codecId,
	             pdu.pixelFormat, pdu.destRect.left, pdu.destRect.top, pdu.destRect.right,
	             pdu.destRect.bottom, pdu.bitmapDataLength);
	cmd.surfaceId = pdu.surfaceId;
	cmd.codecId = pdu.codecId;
	cmd.contextId = 0;

	switch (pdu.pixelFormat)
	{
		case GFX_PIXEL_FORMAT_XRGB_8888:
			cmd.format = PIXEL_FORMAT_BGRX32;
			break;

		case GFX_PIXEL_FORMAT_ARGB_8888:
			cmd.format = PIXEL_FORMAT_BGRA32;
			break;

		default:
			return ERROR_INVALID_DATA;
	}

	cmd.left = pdu.destRect.left;
	cmd.top = pdu.destRect.top;
	cmd.right = pdu.destRect.right;
	cmd.bottom = pdu.destRect.bottom;
	cmd.width = cmd.right - cmd.left;
	cmd.height = cmd.bottom - cmd.top;
	cmd.length = pdu.bitmapDataLength;
	cmd.data = pdu.bitmapData;
	cmd.extra = NULL;

	if (cmd.right < cmd.left)
	{
		WLog_Print(gfx->log, WLOG_ERROR, "RecvWireToSurface1Pdu right=%" PRIu32 " < left=%" PRIu32,
		           cmd.right, cmd.left);
		return ERROR_INVALID_DATA;
	}
	if (cmd.bottom < cmd.top)
	{
		WLog_Print(gfx->log, WLOG_ERROR, "RecvWireToSurface1Pdu bottom=%" PRIu32 " < top=%" PRIu32,
		           cmd.bottom, cmd.top);
		return ERROR_INVALID_DATA;
	}

	if ((error = rdpgfx_decode(gfx, &cmd)))
		WLog_Print(gfx->log, WLOG_ERROR, "rdpgfx_decode failed with error %" PRIu32 "!", error);

	return error;
}

/**
 * Function description
 *
 * @return 0 on success, otherwise a Win32 error code
 */
static UINT rdpgfx_recv_wire_to_surface_2_pdu(GENERIC_CHANNEL_CALLBACK* callback, wStream* s)
{
	RDPGFX_SURFACE_COMMAND cmd = { 0 };
	RDPGFX_WIRE_TO_SURFACE_PDU_2 pdu = { 0 };
	WINPR_ASSERT(callback);
	RDPGFX_PLUGIN* gfx = (RDPGFX_PLUGIN*)callback->plugin;
	WINPR_ASSERT(gfx);
	RdpgfxClientContext* context = gfx->context;
	UINT error = CHANNEL_RC_OK;

	if (!Stream_CheckAndLogRequiredLength(TAG, s, RDPGFX_WIRE_TO_SURFACE_PDU_2_SIZE))
		return ERROR_INVALID_DATA;

	Stream_Read_UINT16(s, pdu.surfaceId);        /* surfaceId (2 bytes) */
	Stream_Read_UINT16(s, pdu.codecId);          /* codecId (2 bytes) */
	Stream_Read_UINT32(s, pdu.codecContextId);   /* codecContextId (4 bytes) */
	Stream_Read_UINT8(s, pdu.pixelFormat);       /* pixelFormat (1 byte) */
	Stream_Read_UINT32(s, pdu.bitmapDataLength); /* bitmapDataLength (4 bytes) */
	pdu.bitmapData = Stream_Pointer(s);
	Stream_Seek(s, pdu.bitmapDataLength);

	DEBUG_RDPGFX(gfx->log,
	             "RecvWireToSurface2Pdu: surfaceId: %" PRIu16 " codecId: %s (0x%04" PRIX16 ") "
	             "codecContextId: %" PRIu32 " pixelFormat: 0x%02" PRIX8
	             " bitmapDataLength: %" PRIu32 "",
	             pdu.surfaceId, rdpgfx_get_codec_id_string(pdu.codecId), pdu.codecId,
	             pdu.codecContextId, pdu.pixelFormat, pdu.bitmapDataLength);

	cmd.surfaceId = pdu.surfaceId;
	cmd.codecId = pdu.codecId;
	cmd.contextId = pdu.codecContextId;

	switch (pdu.pixelFormat)
	{
		case GFX_PIXEL_FORMAT_XRGB_8888:
			cmd.format = PIXEL_FORMAT_BGRX32;
			break;

		case GFX_PIXEL_FORMAT_ARGB_8888:
			cmd.format = PIXEL_FORMAT_BGRA32;
			break;

		default:
			return ERROR_INVALID_DATA;
	}

	cmd.left = 0;
	cmd.top = 0;
	cmd.right = 0;
	cmd.bottom = 0;
	cmd.width = 0;
	cmd.height = 0;
	cmd.length = pdu.bitmapDataLength;
	cmd.data = pdu.bitmapData;
	cmd.extra = NULL;

	if (context)
	{
		IFCALLRET(context->SurfaceCommand, error, context, &cmd);

		if (error)
			WLog_Print(gfx->log, WLOG_ERROR,
			           "context->SurfaceCommand failed with error %" PRIu32 "", error);
	}

	return error;
}

/**
 * Function description
 *
 * @return 0 on success, otherwise a Win32 error code
 */
static UINT rdpgfx_recv_delete_encoding_context_pdu(GENERIC_CHANNEL_CALLBACK* callback, wStream* s)
{
	RDPGFX_DELETE_ENCODING_CONTEXT_PDU pdu = { 0 };
	WINPR_ASSERT(callback);
	RDPGFX_PLUGIN* gfx = (RDPGFX_PLUGIN*)callback->plugin;
	WINPR_ASSERT(gfx);
	RdpgfxClientContext* context = gfx->context;
	UINT error = CHANNEL_RC_OK;

	if (!Stream_CheckAndLogRequiredLength(TAG, s, 6))
		return ERROR_INVALID_DATA;

	Stream_Read_UINT16(s, pdu.surfaceId);      /* surfaceId (2 bytes) */
	Stream_Read_UINT32(s, pdu.codecContextId); /* codecContextId (4 bytes) */

	DEBUG_RDPGFX(gfx->log,
	             "RecvDeleteEncodingContextPdu: surfaceId: %" PRIu16 " codecContextId: %" PRIu32 "",
	             pdu.surfaceId, pdu.codecContextId);

	if (context)
	{
		IFCALLRET(context->DeleteEncodingContext, error, context, &pdu);

		if (error)
			WLog_Print(gfx->log, WLOG_ERROR,
			           "context->DeleteEncodingContext failed with error %" PRIu32 "", error);
	}

	return error;
}

/**
 * Function description
 *
 * @return 0 on success, otherwise a Win32 error code
 */
static UINT rdpgfx_recv_solid_fill_pdu(GENERIC_CHANNEL_CALLBACK* callback, wStream* s)
{
	RECTANGLE_16* fillRect = NULL;
	RDPGFX_SOLID_FILL_PDU pdu = { 0 };
	WINPR_ASSERT(callback);
	RDPGFX_PLUGIN* gfx = (RDPGFX_PLUGIN*)callback->plugin;
	WINPR_ASSERT(gfx);
	RdpgfxClientContext* context = gfx->context;
	UINT error = 0;

	if (!Stream_CheckAndLogRequiredLength(TAG, s, 8))
		return ERROR_INVALID_DATA;

	Stream_Read_UINT16(s, pdu.surfaceId); /* surfaceId (2 bytes) */

	if ((error = rdpgfx_read_color32(s, &(pdu.fillPixel)))) /* fillPixel (4 bytes) */
	{
		WLog_Print(gfx->log, WLOG_ERROR, "rdpgfx_read_color32 failed with error %" PRIu32 "!",
		           error);
		return error;
	}

	Stream_Read_UINT16(s, pdu.fillRectCount); /* fillRectCount (2 bytes) */

	if (!Stream_CheckAndLogRequiredLengthOfSize(TAG, s, pdu.fillRectCount, 8ull))
		return ERROR_INVALID_DATA;

	pdu.fillRects = (RECTANGLE_16*)calloc(pdu.fillRectCount, sizeof(RECTANGLE_16));

	if (!pdu.fillRects)
	{
		WLog_Print(gfx->log, WLOG_ERROR, "calloc failed!");
		return CHANNEL_RC_NO_MEMORY;
	}

	for (UINT16 index = 0; index < pdu.fillRectCount; index++)
	{
		fillRect = &(pdu.fillRects[index]);

		if ((error = rdpgfx_read_rect16(s, fillRect)))
		{
			WLog_Print(gfx->log, WLOG_ERROR, "rdpgfx_read_rect16 failed with error %" PRIu32 "!",
			           error);
			free(pdu.fillRects);
			return error;
		}
	}
	DEBUG_RDPGFX(gfx->log, "RecvSolidFillPdu: surfaceId: %" PRIu16 " fillRectCount: %" PRIu16 "",
	             pdu.surfaceId, pdu.fillRectCount);

	if (context)
	{
		IFCALLRET(context->SolidFill, error, context, &pdu);

		if (error)
			WLog_Print(gfx->log, WLOG_ERROR, "context->SolidFill failed with error %" PRIu32 "",
			           error);
	}

	free(pdu.fillRects);
	return error;
}

/**
 * Function description
 *
 * @return 0 on success, otherwise a Win32 error code
 */
static UINT rdpgfx_recv_surface_to_surface_pdu(GENERIC_CHANNEL_CALLBACK* callback, wStream* s)
{
	RDPGFX_POINT16* destPt = NULL;
	RDPGFX_SURFACE_TO_SURFACE_PDU pdu = { 0 };
	WINPR_ASSERT(callback);
	RDPGFX_PLUGIN* gfx = (RDPGFX_PLUGIN*)callback->plugin;
	WINPR_ASSERT(gfx);
	RdpgfxClientContext* context = gfx->context;
	UINT error = 0;

	if (!Stream_CheckAndLogRequiredLength(TAG, s, 14))
		return ERROR_INVALID_DATA;

	Stream_Read_UINT16(s, pdu.surfaceIdSrc);  /* surfaceIdSrc (2 bytes) */
	Stream_Read_UINT16(s, pdu.surfaceIdDest); /* surfaceIdDest (2 bytes) */

	if ((error = rdpgfx_read_rect16(s, &(pdu.rectSrc)))) /* rectSrc (8 bytes ) */
	{
		WLog_Print(gfx->log, WLOG_ERROR, "rdpgfx_read_rect16 failed with error %" PRIu32 "!",
		           error);
		return error;
	}

	Stream_Read_UINT16(s, pdu.destPtsCount); /* destPtsCount (2 bytes) */

	if (!Stream_CheckAndLogRequiredLengthOfSize(TAG, s, pdu.destPtsCount, 4ull))
		return ERROR_INVALID_DATA;

	pdu.destPts = (RDPGFX_POINT16*)calloc(pdu.destPtsCount, sizeof(RDPGFX_POINT16));

	if (!pdu.destPts)
	{
		WLog_Print(gfx->log, WLOG_ERROR, "calloc failed!");
		return CHANNEL_RC_NO_MEMORY;
	}

	for (UINT16 index = 0; index < pdu.destPtsCount; index++)
	{
		destPt = &(pdu.destPts[index]);

		if ((error = rdpgfx_read_point16(s, destPt)))
		{
			WLog_Print(gfx->log, WLOG_ERROR, "rdpgfx_read_point16 failed with error %" PRIu32 "!",
			           error);
			free(pdu.destPts);
			return error;
		}
	}

	DEBUG_RDPGFX(gfx->log,
	             "RecvSurfaceToSurfacePdu: surfaceIdSrc: %" PRIu16 " surfaceIdDest: %" PRIu16 " "
	             "left: %" PRIu16 " top: %" PRIu16 " right: %" PRIu16 " bottom: %" PRIu16
	             " destPtsCount: %" PRIu16 "",
	             pdu.surfaceIdSrc, pdu.surfaceIdDest, pdu.rectSrc.left, pdu.rectSrc.top,
	             pdu.rectSrc.right, pdu.rectSrc.bottom, pdu.destPtsCount);

	if (context)
	{
		IFCALLRET(context->SurfaceToSurface, error, context, &pdu);

		if (error)
			WLog_Print(gfx->log, WLOG_ERROR,
			           "context->SurfaceToSurface failed with error %" PRIu32 "", error);
	}

	free(pdu.destPts);
	return error;
}

/**
 * Function description
 *
 * @return 0 on success, otherwise a Win32 error code
 */
static UINT rdpgfx_recv_surface_to_cache_pdu(GENERIC_CHANNEL_CALLBACK* callback, wStream* s)
{
	RDPGFX_SURFACE_TO_CACHE_PDU pdu = { 0 };
	WINPR_ASSERT(callback);
	RDPGFX_PLUGIN* gfx = (RDPGFX_PLUGIN*)callback->plugin;

	WINPR_ASSERT(gfx);
	RdpgfxClientContext* context = gfx->context;
	UINT error = 0;

	if (!Stream_CheckAndLogRequiredLength(TAG, s, 20))
		return ERROR_INVALID_DATA;

	Stream_Read_UINT16(s, pdu.surfaceId); /* surfaceId (2 bytes) */
	Stream_Read_UINT64(s, pdu.cacheKey);  /* cacheKey (8 bytes) */
	Stream_Read_UINT16(s, pdu.cacheSlot); /* cacheSlot (2 bytes) */

	if ((error = rdpgfx_read_rect16(s, &(pdu.rectSrc)))) /* rectSrc (8 bytes ) */
	{
		WLog_Print(gfx->log, WLOG_ERROR, "rdpgfx_read_rect16 failed with error %" PRIu32 "!",
		           error);
		return error;
	}

	DEBUG_RDPGFX(gfx->log,
	             "RecvSurfaceToCachePdu: surfaceId: %" PRIu16 " cacheKey: 0x%016" PRIX64
	             " cacheSlot: %" PRIu16 " "
	             "left: %" PRIu16 " top: %" PRIu16 " right: %" PRIu16 " bottom: %" PRIu16 "",
	             pdu.surfaceId, pdu.cacheKey, pdu.cacheSlot, pdu.rectSrc.left, pdu.rectSrc.top,
	             pdu.rectSrc.right, pdu.rectSrc.bottom);

	if (context)
	{
		IFCALLRET(context->SurfaceToCache, error, context, &pdu);

		if (error)
			WLog_Print(gfx->log, WLOG_ERROR,
			           "context->SurfaceToCache failed with error %" PRIu32 "", error);
	}

	return error;
}

/**
 * Function description
 *
 * @return 0 on success, otherwise a Win32 error code
 */
static UINT rdpgfx_recv_cache_to_surface_pdu(GENERIC_CHANNEL_CALLBACK* callback, wStream* s)
{
	RDPGFX_POINT16* destPt = NULL;
	RDPGFX_CACHE_TO_SURFACE_PDU pdu = { 0 };
	WINPR_ASSERT(callback);
	RDPGFX_PLUGIN* gfx = (RDPGFX_PLUGIN*)callback->plugin;

	WINPR_ASSERT(gfx);
	RdpgfxClientContext* context = gfx->context;
	UINT error = CHANNEL_RC_OK;

	if (!Stream_CheckAndLogRequiredLength(TAG, s, 6))
		return ERROR_INVALID_DATA;

	Stream_Read_UINT16(s, pdu.cacheSlot);    /* cacheSlot (2 bytes) */
	Stream_Read_UINT16(s, pdu.surfaceId);    /* surfaceId (2 bytes) */
	Stream_Read_UINT16(s, pdu.destPtsCount); /* destPtsCount (2 bytes) */

	if (!Stream_CheckAndLogRequiredLengthOfSize(TAG, s, pdu.destPtsCount, 4ull))
		return ERROR_INVALID_DATA;

	pdu.destPts = (RDPGFX_POINT16*)calloc(pdu.destPtsCount, sizeof(RDPGFX_POINT16));

	if (!pdu.destPts)
	{
		WLog_Print(gfx->log, WLOG_ERROR, "calloc failed!");
		return CHANNEL_RC_NO_MEMORY;
	}

	for (UINT16 index = 0; index < pdu.destPtsCount; index++)
	{
		destPt = &(pdu.destPts[index]);

		if ((error = rdpgfx_read_point16(s, destPt)))
		{
			WLog_Print(gfx->log, WLOG_ERROR, "rdpgfx_read_point16 failed with error %" PRIu32 "",
			           error);
			free(pdu.destPts);
			return error;
		}
	}

	DEBUG_RDPGFX(gfx->log,
	             "RdpGfxRecvCacheToSurfacePdu: cacheSlot: %" PRIu16 " surfaceId: %" PRIu16
	             " destPtsCount: %" PRIu16 "",
	             pdu.cacheSlot, pdu.surfaceId, pdu.destPtsCount);

	if (context)
	{
		IFCALLRET(context->CacheToSurface, error, context, &pdu);

		if (error)
			WLog_Print(gfx->log, WLOG_ERROR,
			           "context->CacheToSurface failed with error %" PRIu32 "", error);
	}

	free(pdu.destPts);
	return error;
}

/**
 * Function description
 *
 * @return 0 on success, otherwise a Win32 error code
 */
static UINT rdpgfx_recv_map_surface_to_output_pdu(GENERIC_CHANNEL_CALLBACK* callback, wStream* s)
{
	RDPGFX_MAP_SURFACE_TO_OUTPUT_PDU pdu = { 0 };
	WINPR_ASSERT(callback);
	RDPGFX_PLUGIN* gfx = (RDPGFX_PLUGIN*)callback->plugin;

	WINPR_ASSERT(gfx);
	RdpgfxClientContext* context = gfx->context;
	UINT error = CHANNEL_RC_OK;

	if (!Stream_CheckAndLogRequiredLength(TAG, s, 12))
		return ERROR_INVALID_DATA;

	Stream_Read_UINT16(s, pdu.surfaceId);     /* surfaceId (2 bytes) */
	Stream_Read_UINT16(s, pdu.reserved);      /* reserved (2 bytes) */
	Stream_Read_UINT32(s, pdu.outputOriginX); /* outputOriginX (4 bytes) */
	Stream_Read_UINT32(s, pdu.outputOriginY); /* outputOriginY (4 bytes) */
	DEBUG_RDPGFX(gfx->log,
	             "RecvMapSurfaceToOutputPdu: surfaceId: %" PRIu16 " outputOriginX: %" PRIu32
	             " outputOriginY: %" PRIu32 "",
	             pdu.surfaceId, pdu.outputOriginX, pdu.outputOriginY);

	if (context)
	{
		IFCALLRET(context->MapSurfaceToOutput, error, context, &pdu);

		if (error)
			WLog_Print(gfx->log, WLOG_ERROR,
			           "context->MapSurfaceToOutput failed with error %" PRIu32 "", error);
	}

	return error;
}

static UINT rdpgfx_recv_map_surface_to_scaled_output_pdu(GENERIC_CHANNEL_CALLBACK* callback,
                                                         wStream* s)
{
	RDPGFX_MAP_SURFACE_TO_SCALED_OUTPUT_PDU pdu = { 0 };
	WINPR_ASSERT(callback);
	RDPGFX_PLUGIN* gfx = (RDPGFX_PLUGIN*)callback->plugin;

	WINPR_ASSERT(gfx);
	RdpgfxClientContext* context = gfx->context;
	UINT error = CHANNEL_RC_OK;

	if (!Stream_CheckAndLogRequiredLength(TAG, s, 20))
		return ERROR_INVALID_DATA;

	Stream_Read_UINT16(s, pdu.surfaceId);     /* surfaceId (2 bytes) */
	Stream_Read_UINT16(s, pdu.reserved);      /* reserved (2 bytes) */
	Stream_Read_UINT32(s, pdu.outputOriginX); /* outputOriginX (4 bytes) */
	Stream_Read_UINT32(s, pdu.outputOriginY); /* outputOriginY (4 bytes) */
	Stream_Read_UINT32(s, pdu.targetWidth);   /* targetWidth (4 bytes) */
	Stream_Read_UINT32(s, pdu.targetHeight);  /* targetHeight (4 bytes) */
	DEBUG_RDPGFX(gfx->log,
	             "RecvMapSurfaceToScaledOutputPdu: surfaceId: %" PRIu16 " outputOriginX: %" PRIu32
	             " outputOriginY: %" PRIu32 " targetWidth: %" PRIu32 " targetHeight: %" PRIu32,
	             pdu.surfaceId, pdu.outputOriginX, pdu.outputOriginY, pdu.targetWidth,
	             pdu.targetHeight);

	if (context)
	{
		IFCALLRET(context->MapSurfaceToScaledOutput, error, context, &pdu);

		if (error)
			WLog_Print(gfx->log, WLOG_ERROR,
			           "context->MapSurfaceToScaledOutput failed with error %" PRIu32 "", error);
	}

	return error;
}

/**
 * Function description
 *
 * @return 0 on success, otherwise a Win32 error code
 */
static UINT rdpgfx_recv_map_surface_to_window_pdu(GENERIC_CHANNEL_CALLBACK* callback, wStream* s)
{
	RDPGFX_MAP_SURFACE_TO_WINDOW_PDU pdu = { 0 };
	WINPR_ASSERT(callback);
	RDPGFX_PLUGIN* gfx = (RDPGFX_PLUGIN*)callback->plugin;

	WINPR_ASSERT(gfx);
	RdpgfxClientContext* context = gfx->context;
	UINT error = CHANNEL_RC_OK;

	if (!Stream_CheckAndLogRequiredLength(TAG, s, 18))
		return ERROR_INVALID_DATA;

	Stream_Read_UINT16(s, pdu.surfaceId);    /* surfaceId (2 bytes) */
	Stream_Read_UINT64(s, pdu.windowId);     /* windowId (8 bytes) */
	Stream_Read_UINT32(s, pdu.mappedWidth);  /* mappedWidth (4 bytes) */
	Stream_Read_UINT32(s, pdu.mappedHeight); /* mappedHeight (4 bytes) */
	DEBUG_RDPGFX(gfx->log,
	             "RecvMapSurfaceToWindowPdu: surfaceId: %" PRIu16 " windowId: 0x%016" PRIX64
	             " mappedWidth: %" PRIu32 " mappedHeight: %" PRIu32 "",
	             pdu.surfaceId, pdu.windowId, pdu.mappedWidth, pdu.mappedHeight);

	if (context && context->MapSurfaceToWindow)
	{
		IFCALLRET(context->MapSurfaceToWindow, error, context, &pdu);

		if (error)
			WLog_Print(gfx->log, WLOG_ERROR,
			           "context->MapSurfaceToWindow failed with error %" PRIu32 "", error);
	}

	return error;
}

static UINT rdpgfx_recv_map_surface_to_scaled_window_pdu(GENERIC_CHANNEL_CALLBACK* callback,
                                                         wStream* s)
{
	RDPGFX_MAP_SURFACE_TO_SCALED_WINDOW_PDU pdu = { 0 };
	WINPR_ASSERT(callback);
	RDPGFX_PLUGIN* gfx = (RDPGFX_PLUGIN*)callback->plugin;
	WINPR_ASSERT(gfx);
	RdpgfxClientContext* context = gfx->context;
	UINT error = CHANNEL_RC_OK;

	if (!Stream_CheckAndLogRequiredLength(TAG, s, 26))
		return ERROR_INVALID_DATA;

	Stream_Read_UINT16(s, pdu.surfaceId);    /* surfaceId (2 bytes) */
	Stream_Read_UINT64(s, pdu.windowId);     /* windowId (8 bytes) */
	Stream_Read_UINT32(s, pdu.mappedWidth);  /* mappedWidth (4 bytes) */
	Stream_Read_UINT32(s, pdu.mappedHeight); /* mappedHeight (4 bytes) */
	Stream_Read_UINT32(s, pdu.targetWidth);  /* targetWidth (4 bytes) */
	Stream_Read_UINT32(s, pdu.targetHeight); /* targetHeight (4 bytes) */
	DEBUG_RDPGFX(gfx->log,
	             "RecvMapSurfaceToScaledWindowPdu: surfaceId: %" PRIu16 " windowId: 0x%016" PRIX64
	             " mappedWidth: %" PRIu32 " mappedHeight: %" PRIu32 " targetWidth: %" PRIu32
	             " targetHeight: %" PRIu32 "",
	             pdu.surfaceId, pdu.windowId, pdu.mappedWidth, pdu.mappedHeight, pdu.targetWidth,
	             pdu.targetHeight);

	if (context && context->MapSurfaceToScaledWindow)
	{
		IFCALLRET(context->MapSurfaceToScaledWindow, error, context, &pdu);

		if (error)
			WLog_Print(gfx->log, WLOG_ERROR,
			           "context->MapSurfaceToScaledWindow failed with error %" PRIu32 "", error);
	}

	return error;
}

/**
 * Function description
 *
 * @return 0 on success, otherwise a Win32 error code
 */
static UINT rdpgfx_recv_pdu(GENERIC_CHANNEL_CALLBACK* callback, wStream* s)
{
	size_t end = 0;
	RDPGFX_HEADER header = { 0 };
	UINT error = 0;
	WINPR_ASSERT(callback);
	RDPGFX_PLUGIN* gfx = (RDPGFX_PLUGIN*)callback->plugin;
	const size_t beg = Stream_GetPosition(s);

	WINPR_ASSERT(gfx);
	if ((error = rdpgfx_read_header(s, &header)))
	{
		WLog_Print(gfx->log, WLOG_ERROR, "rdpgfx_read_header failed with error %" PRIu32 "!",
		           error);
		return error;
	}

	DEBUG_RDPGFX(
	    gfx->log, "cmdId: %s (0x%04" PRIX16 ") flags: 0x%04" PRIX16 " pduLength: %" PRIu32 "",
	    rdpgfx_get_cmd_id_string(header.cmdId), header.cmdId, header.flags, header.pduLength);

	switch (header.cmdId)
	{
		case RDPGFX_CMDID_WIRETOSURFACE_1:
			if ((error = rdpgfx_recv_wire_to_surface_1_pdu(callback, s)))
				WLog_Print(gfx->log, WLOG_ERROR,
				           "rdpgfx_recv_wire_to_surface_1_pdu failed with error %" PRIu32 "!",
				           error);

			break;

		case RDPGFX_CMDID_WIRETOSURFACE_2:
			if ((error = rdpgfx_recv_wire_to_surface_2_pdu(callback, s)))
				WLog_Print(gfx->log, WLOG_ERROR,
				           "rdpgfx_recv_wire_to_surface_2_pdu failed with error %" PRIu32 "!",
				           error);

			break;

		case RDPGFX_CMDID_DELETEENCODINGCONTEXT:
			if ((error = rdpgfx_recv_delete_encoding_context_pdu(callback, s)))
				WLog_Print(gfx->log, WLOG_ERROR,
				           "rdpgfx_recv_delete_encoding_context_pdu failed with error %" PRIu32 "!",
				           error);

			break;

		case RDPGFX_CMDID_SOLIDFILL:
			if ((error = rdpgfx_recv_solid_fill_pdu(callback, s)))
				WLog_Print(gfx->log, WLOG_ERROR,
				           "rdpgfx_recv_solid_fill_pdu failed with error %" PRIu32 "!", error);

			break;

		case RDPGFX_CMDID_SURFACETOSURFACE:
			if ((error = rdpgfx_recv_surface_to_surface_pdu(callback, s)))
				WLog_Print(gfx->log, WLOG_ERROR,
				           "rdpgfx_recv_surface_to_surface_pdu failed with error %" PRIu32 "!",
				           error);

			break;

		case RDPGFX_CMDID_SURFACETOCACHE:
			if ((error = rdpgfx_recv_surface_to_cache_pdu(callback, s)))
				WLog_Print(gfx->log, WLOG_ERROR,
				           "rdpgfx_recv_surface_to_cache_pdu failed with error %" PRIu32 "!",
				           error);

			break;

		case RDPGFX_CMDID_CACHETOSURFACE:
			if ((error = rdpgfx_recv_cache_to_surface_pdu(callback, s)))
				WLog_Print(gfx->log, WLOG_ERROR,
				           "rdpgfx_recv_cache_to_surface_pdu failed with error %" PRIu32 "!",
				           error);

			break;

		case RDPGFX_CMDID_EVICTCACHEENTRY:
			if ((error = rdpgfx_recv_evict_cache_entry_pdu(callback, s)))
				WLog_Print(gfx->log, WLOG_ERROR,
				           "rdpgfx_recv_evict_cache_entry_pdu failed with error %" PRIu32 "!",
				           error);

			break;

		case RDPGFX_CMDID_CREATESURFACE:
			if ((error = rdpgfx_recv_create_surface_pdu(callback, s)))
				WLog_Print(gfx->log, WLOG_ERROR,
				           "rdpgfx_recv_create_surface_pdu failed with error %" PRIu32 "!", error);

			break;

		case RDPGFX_CMDID_DELETESURFACE:
			if ((error = rdpgfx_recv_delete_surface_pdu(callback, s)))
				WLog_Print(gfx->log, WLOG_ERROR,
				           "rdpgfx_recv_delete_surface_pdu failed with error %" PRIu32 "!", error);

			break;

		case RDPGFX_CMDID_STARTFRAME:
			if ((error = rdpgfx_recv_start_frame_pdu(callback, s)))
				WLog_Print(gfx->log, WLOG_ERROR,
				           "rdpgfx_recv_start_frame_pdu failed with error %" PRIu32 "!", error);

			break;

		case RDPGFX_CMDID_ENDFRAME:
			if ((error = rdpgfx_recv_end_frame_pdu(callback, s)))
				WLog_Print(gfx->log, WLOG_ERROR,
				           "rdpgfx_recv_end_frame_pdu failed with error %" PRIu32 "!", error);

			break;

		case RDPGFX_CMDID_RESETGRAPHICS:
			if ((error = rdpgfx_recv_reset_graphics_pdu(callback, s)))
				WLog_Print(gfx->log, WLOG_ERROR,
				           "rdpgfx_recv_reset_graphics_pdu failed with error %" PRIu32 "!", error);

			break;

		case RDPGFX_CMDID_MAPSURFACETOOUTPUT:
			if ((error = rdpgfx_recv_map_surface_to_output_pdu(callback, s)))
				WLog_Print(gfx->log, WLOG_ERROR,
				           "rdpgfx_recv_map_surface_to_output_pdu failed with error %" PRIu32 "!",
				           error);

			break;

		case RDPGFX_CMDID_CACHEIMPORTREPLY:
			if ((error = rdpgfx_recv_cache_import_reply_pdu(callback, s)))
				WLog_Print(gfx->log, WLOG_ERROR,
				           "rdpgfx_recv_cache_import_reply_pdu failed with error %" PRIu32 "!",
				           error);

			break;

		case RDPGFX_CMDID_CAPSCONFIRM:
			if ((error = rdpgfx_recv_caps_confirm_pdu(callback, s)))
				WLog_Print(gfx->log, WLOG_ERROR,
				           "rdpgfx_recv_caps_confirm_pdu failed with error %" PRIu32 "!", error);

			if ((error = rdpgfx_send_cache_offer(gfx)))
				WLog_Print(gfx->log, WLOG_ERROR,
				           "rdpgfx_send_cache_offer failed with error %" PRIu32 "!", error);

			break;

		case RDPGFX_CMDID_MAPSURFACETOWINDOW:
			if ((error = rdpgfx_recv_map_surface_to_window_pdu(callback, s)))
				WLog_Print(gfx->log, WLOG_ERROR,
				           "rdpgfx_recv_map_surface_to_window_pdu failed with error %" PRIu32 "!",
				           error);

			break;

		case RDPGFX_CMDID_MAPSURFACETOSCALEDWINDOW:
			if ((error = rdpgfx_recv_map_surface_to_scaled_window_pdu(callback, s)))
				WLog_Print(gfx->log, WLOG_ERROR,
				           "rdpgfx_recv_map_surface_to_scaled_window_pdu failed with error %" PRIu32
				           "!",
				           error);

			break;

		case RDPGFX_CMDID_MAPSURFACETOSCALEDOUTPUT:
			if ((error = rdpgfx_recv_map_surface_to_scaled_output_pdu(callback, s)))
				WLog_Print(gfx->log, WLOG_ERROR,
				           "rdpgfx_recv_map_surface_to_scaled_output_pdu failed with error %" PRIu32
				           "!",
				           error);

			break;

		default:
			error = CHANNEL_RC_BAD_PROC;
			break;
	}

	if (error)
	{
		WLog_Print(gfx->log, WLOG_ERROR, "Error while processing GFX cmdId: %s (0x%04" PRIX16 ")",
		           rdpgfx_get_cmd_id_string(header.cmdId), header.cmdId);
		Stream_SetPosition(s, (beg + header.pduLength));
		return error;
	}

	end = Stream_GetPosition(s);

	if (end != (beg + header.pduLength))
	{
		WLog_Print(gfx->log, WLOG_ERROR,
		           "Unexpected gfx pdu end: Actual: %" PRIuz ", Expected: %" PRIuz, end,
		           (beg + header.pduLength));
		Stream_SetPosition(s, (beg + header.pduLength));
	}

	return error;
}

/**
 * Function description
 *
 * @return 0 on success, otherwise a Win32 error code
 */
static UINT rdpgfx_on_data_received(IWTSVirtualChannelCallback* pChannelCallback, wStream* data)
{
	wStream* s = NULL;
	int status = 0;
	UINT32 DstSize = 0;
	BYTE* pDstData = NULL;
	GENERIC_CHANNEL_CALLBACK* callback = (GENERIC_CHANNEL_CALLBACK*)pChannelCallback;
	WINPR_ASSERT(callback);
	RDPGFX_PLUGIN* gfx = (RDPGFX_PLUGIN*)callback->plugin;
	UINT error = CHANNEL_RC_OK;

	WINPR_ASSERT(gfx);
	status = zgfx_decompress(gfx->zgfx, Stream_ConstPointer(data),
	                         (UINT32)Stream_GetRemainingLength(data), &pDstData, &DstSize, 0);

	if (status < 0)
	{
		WLog_Print(gfx->log, WLOG_ERROR, "zgfx_decompress failure! status: %d", status);
		return ERROR_INTERNAL_ERROR;
	}

	s = Stream_New(pDstData, DstSize);

	if (!s)
	{
		WLog_Print(gfx->log, WLOG_ERROR, "calloc failed!");
		return CHANNEL_RC_NO_MEMORY;
	}

	while (Stream_GetPosition(s) < Stream_Length(s))
	{
		if ((error = rdpgfx_recv_pdu(callback, s)))
		{
			WLog_Print(gfx->log, WLOG_ERROR, "rdpgfx_recv_pdu failed with error %" PRIu32 "!",
			           error);
			break;
		}
	}

	Stream_Free(s, TRUE);
	return error;
}

/**
 * Function description
 *
 * @return 0 on success, otherwise a Win32 error code
 */
static UINT rdpgfx_on_open(IWTSVirtualChannelCallback* pChannelCallback)
{
	GENERIC_CHANNEL_CALLBACK* callback = (GENERIC_CHANNEL_CALLBACK*)pChannelCallback;
	WINPR_ASSERT(callback);
	RDPGFX_PLUGIN* gfx = (RDPGFX_PLUGIN*)callback->plugin;
	WINPR_ASSERT(gfx);
	RdpgfxClientContext* context = gfx->context;
	UINT error = CHANNEL_RC_OK;
	BOOL do_caps_advertise = TRUE;
	gfx->sendFrameAcks = TRUE;

	if (context)
	{
		IFCALLRET(context->OnOpen, error, context, &do_caps_advertise, &gfx->sendFrameAcks);

		if (error)
			WLog_Print(gfx->log, WLOG_ERROR, "context->OnOpen failed with error %" PRIu32 "",
			           error);
	}

	if (do_caps_advertise)
		error = rdpgfx_send_supported_caps(callback);

	return error;
}

/**
 * Function description
 *
 * @return 0 on success, otherwise a Win32 error code
 */
static UINT rdpgfx_on_close(IWTSVirtualChannelCallback* pChannelCallback)
{
	UINT error = CHANNEL_RC_OK;
	GENERIC_CHANNEL_CALLBACK* callback = (GENERIC_CHANNEL_CALLBACK*)pChannelCallback;
	WINPR_ASSERT(callback);
	RDPGFX_PLUGIN* gfx = (RDPGFX_PLUGIN*)callback->plugin;

	if (!gfx)
		goto fail;

	RdpgfxClientContext* context = gfx->context;

	DEBUG_RDPGFX(gfx->log, "OnClose");
	error = rdpgfx_save_persistent_cache(gfx);

	if (error)
	{
		// print error, but don't consider this a hard failure
		WLog_Print(gfx->log, WLOG_ERROR,
		           "rdpgfx_save_persistent_cache failed with error %" PRIu32 "", error);
	}

	free_surfaces(context, gfx->SurfaceTable);
	evict_cache_slots(context, gfx->MaxCacheSlots, gfx->CacheSlots);

	free(callback);
	gfx->UnacknowledgedFrames = 0;
	gfx->TotalDecodedFrames = 0;

	if (context)
	{
		IFCALL(context->OnClose, context);
	}

fail:
	return CHANNEL_RC_OK;
}

static void terminate_plugin_cb(GENERIC_DYNVC_PLUGIN* base)
{
	RDPGFX_PLUGIN* gfx = (RDPGFX_PLUGIN*)base;
	WINPR_ASSERT(gfx);
	RdpgfxClientContext* context = gfx->context;

	DEBUG_RDPGFX(gfx->log, "Terminated");
	rdpgfx_client_context_free(context);
}

/**
 * Function description
 *
 * @return 0 on success, otherwise a Win32 error code
 */
static UINT rdpgfx_set_surface_data(RdpgfxClientContext* context, UINT16 surfaceId, void* pData)
{
	ULONG_PTR key = 0;
	WINPR_ASSERT(context);
	RDPGFX_PLUGIN* gfx = (RDPGFX_PLUGIN*)context->handle;
	WINPR_ASSERT(gfx);
	key = ((ULONG_PTR)surfaceId) + 1;

	if (pData)
	{
		if (!HashTable_Insert(gfx->SurfaceTable, (void*)key, pData))
			return ERROR_BAD_ARGUMENTS;
	}
	else
		HashTable_Remove(gfx->SurfaceTable, (void*)key);

	return CHANNEL_RC_OK;
}

/**
 * Function description
 *
 * @return 0 on success, otherwise a Win32 error code
 */
static UINT rdpgfx_get_surface_ids(RdpgfxClientContext* context, UINT16** ppSurfaceIds,
                                   UINT16* count_out)
{
	size_t count = 0;
	UINT16* pSurfaceIds = NULL;
	ULONG_PTR* pKeys = NULL;
	WINPR_ASSERT(context);
	RDPGFX_PLUGIN* gfx = (RDPGFX_PLUGIN*)context->handle;
	WINPR_ASSERT(gfx);
	count = HashTable_GetKeys(gfx->SurfaceTable, &pKeys);

	WINPR_ASSERT(ppSurfaceIds);
	WINPR_ASSERT(count_out);
	if (count < 1)
	{
		*count_out = 0;
		return CHANNEL_RC_OK;
	}

	pSurfaceIds = (UINT16*)calloc(count, sizeof(UINT16));

	if (!pSurfaceIds)
	{
		WLog_Print(gfx->log, WLOG_ERROR, "calloc failed!");
		free(pKeys);
		return CHANNEL_RC_NO_MEMORY;
	}

	for (size_t index = 0; index < count; index++)
	{
		pSurfaceIds[index] = (UINT16)(pKeys[index] - 1);
	}

	free(pKeys);
	*ppSurfaceIds = pSurfaceIds;
	*count_out = (UINT16)count;
	return CHANNEL_RC_OK;
}

static void* rdpgfx_get_surface_data(RdpgfxClientContext* context, UINT16 surfaceId)
{
	ULONG_PTR key = 0;
	void* pData = NULL;
	WINPR_ASSERT(context);
	RDPGFX_PLUGIN* gfx = (RDPGFX_PLUGIN*)context->handle;
	WINPR_ASSERT(gfx);
	key = ((ULONG_PTR)surfaceId) + 1;
	pData = HashTable_GetItemValue(gfx->SurfaceTable, (void*)key);
	return pData;
}

/**
 * Function description
 *
 * @return 0 on success, otherwise a Win32 error code
 */
static UINT rdpgfx_set_cache_slot_data(RdpgfxClientContext* context, UINT16 cacheSlot, void* pData)
{
	WINPR_ASSERT(context);
	RDPGFX_PLUGIN* gfx = (RDPGFX_PLUGIN*)context->handle;

	WINPR_ASSERT(gfx);
	/* Microsoft uses 1-based indexing for the egfx bitmap cache ! */
	if (cacheSlot == 0 || cacheSlot > gfx->MaxCacheSlots)
	{
		WLog_ERR(TAG, "invalid cache slot %" PRIu16 ", must be between 1 and %" PRIu16 "",
		         cacheSlot, gfx->MaxCacheSlots);
		return ERROR_INVALID_INDEX;
	}

	gfx->CacheSlots[cacheSlot - 1] = pData;
	return CHANNEL_RC_OK;
}

static void* rdpgfx_get_cache_slot_data(RdpgfxClientContext* context, UINT16 cacheSlot)
{
	void* pData = NULL;
	WINPR_ASSERT(context);
	RDPGFX_PLUGIN* gfx = (RDPGFX_PLUGIN*)context->handle;
	WINPR_ASSERT(gfx);
	/* Microsoft uses 1-based indexing for the egfx bitmap cache ! */
	if (cacheSlot == 0 || cacheSlot > gfx->MaxCacheSlots)
	{
		WLog_ERR(TAG, "invalid cache slot %" PRIu16 ", must be between 1 and %" PRIu16 "",
		         cacheSlot, gfx->MaxCacheSlots);
		return NULL;
	}

	pData = gfx->CacheSlots[cacheSlot - 1];
	return pData;
}

static UINT init_plugin_cb(GENERIC_DYNVC_PLUGIN* base, rdpContext* rcontext, rdpSettings* settings)
{
	RdpgfxClientContext* context = NULL;
	RDPGFX_PLUGIN* gfx = (RDPGFX_PLUGIN*)base;

	WINPR_ASSERT(base);
	gfx->rdpcontext = rcontext;
	gfx->log = WLog_Get(TAG);

	gfx->SurfaceTable = HashTable_New(TRUE);
	if (!gfx->SurfaceTable)
	{
		WLog_ERR(TAG, "HashTable_New for surfaces failed !");
		return CHANNEL_RC_NO_MEMORY;
	}

	gfx->MaxCacheSlots =
	    freerdp_settings_get_bool(gfx->rdpcontext->settings, FreeRDP_GfxSmallCache) ? 4096 : 25600;

	context = (RdpgfxClientContext*)calloc(1, sizeof(RdpgfxClientContext));
	if (!context)
	{
		WLog_ERR(TAG, "context calloc failed!");
		HashTable_Free(gfx->SurfaceTable);
		gfx->SurfaceTable = NULL;
		return CHANNEL_RC_NO_MEMORY;
	}

	gfx->zgfx = zgfx_context_new(FALSE);
	if (!gfx->zgfx)
	{
		WLog_ERR(TAG, "zgfx_context_new failed!");
		HashTable_Free(gfx->SurfaceTable);
		gfx->SurfaceTable = NULL;
		free(context);
		return CHANNEL_RC_NO_MEMORY;
	}

	context->handle = (void*)gfx;
	context->GetSurfaceIds = rdpgfx_get_surface_ids;
	context->SetSurfaceData = rdpgfx_set_surface_data;
	context->GetSurfaceData = rdpgfx_get_surface_data;
	context->SetCacheSlotData = rdpgfx_set_cache_slot_data;
	context->GetCacheSlotData = rdpgfx_get_cache_slot_data;
	context->CapsAdvertise = rdpgfx_send_caps_advertise_pdu;
	context->FrameAcknowledge = rdpgfx_send_frame_acknowledge_pdu;
	context->CacheImportOffer = rdpgfx_send_cache_import_offer_pdu;
	context->QoeFrameAcknowledge = rdpgfx_send_qoe_frame_acknowledge_pdu;

	gfx->base.iface.pInterface = (void*)context;
	gfx->context = context;
	return CHANNEL_RC_OK;
}

void rdpgfx_client_context_free(RdpgfxClientContext* context)
{

	RDPGFX_PLUGIN* gfx = NULL;

	if (!context)
		return;

	gfx = (RDPGFX_PLUGIN*)context->handle;

	free_surfaces(context, gfx->SurfaceTable);
	evict_cache_slots(context, gfx->MaxCacheSlots, gfx->CacheSlots);

	if (gfx->zgfx)
	{
		zgfx_context_free(gfx->zgfx);
		gfx->zgfx = NULL;
	}

	HashTable_Free(gfx->SurfaceTable);
	free(context);
}

static const IWTSVirtualChannelCallback rdpgfx_callbacks = { rdpgfx_on_data_received,
	                                                         rdpgfx_on_open, rdpgfx_on_close,
	                                                         NULL };

/**
 * Function description
 *
 * @return 0 on success, otherwise a Win32 error code
 */
FREERDP_ENTRY_POINT(UINT rdpgfx_DVCPluginEntry(IDRDYNVC_ENTRY_POINTS* pEntryPoints))
{
	return freerdp_generic_DVCPluginEntry(pEntryPoints, TAG, RDPGFX_DVC_CHANNEL_NAME,
	                                      sizeof(RDPGFX_PLUGIN), sizeof(GENERIC_CHANNEL_CALLBACK),
	                                      &rdpgfx_callbacks, init_plugin_cb, terminate_plugin_cb);
}