summaryrefslogtreecommitdiff
path: root/server/red_worker.c
blob: 9d6c08e5fc0d738fee61552f170ab6e6f3f24c75 (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
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
/*
   Copyright (C) 2009 Red Hat, Inc.

   This program is free software; you can redistribute it and/or
   modify it under the terms of the GNU General Public License as
   published by the Free Software Foundation; either version 2 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 General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include <stdio.h>
#include <stdarg.h>
#include <sys/epoll.h>
#include <fcntl.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>
#include <pthread.h>
#include <netinet/tcp.h>
#include <setjmp.h>
#include <openssl/ssl.h>

#include "qxl_dev.h"
#include "vd_interface.h"
#include "region.h"
#include "red.h"
#include "red_worker.h"
#include "cairo.h"
#include "cairo_canvas.h"
#include "gl_canvas.h"
#include "ogl_ctx.h"
#include "ffmpeg_inc.h"
#include "quic.h"
#include "lz.h"
#include "glz_encoder_dictionary.h"
#include "glz_encoder.h"
#include "stat.h"
#include "reds.h"
#include "ring.h"

//#define COMPRESS_STAT
//#define DUMP_BITMAP
#define STREAM_TRACE
//#define PIPE_DEBUG
#define USE_EXCLUDE_RGN
//#define RED_WORKER_STAT
//#define DRAW_ALL
//#define COMPRESS_DEBUG

//#define UPDATE_AREA_BY_TREE

#define CMD_RING_POLL_TIMEOUT 10 //milli
#define CMD_RING_POLL_RETRIES 200

#define DETACH_TIMEOUT 15000000000ULL //nano
#define DETACH_SLEEP_DURATION 10000 //micro

#define DISPLAY_CLIENT_TIMEOUT 15000000000ULL //nano
#define DISPLAY_CLIENT_RETRY_INTERVAL 10000 //micro
#define DISPLAY_MAX_SUB_MESSAGES 10

#define DISPLAY_FREE_LIST_DEFAULT_SIZE 128

#define RED_STREAM_DETACTION_MAX_DELTA ((1000 * 1000 * 1000) / 5) // 1/5 sec
#define RED_STREAM_CONTINUS_MAX_DELTA ((1000 * 1000 * 1000) / 2) // 1/2 sec
#define RED_STREAM_TIMOUT (1000 * 1000 * 1000)
#define RED_STREAM_FRAMES_START_CONDITION 20
#define RED_STREAM_GRADUAL_FRAMES_START_CONDITION 0.2
#define RED_STREAM_FRAMES_RESET_CONDITION 100

#define FPS_TEST_INTERVAL 1
#define MAX_FPS 30

//best bit rate per pixel base on 13000000 bps for frame size 720x576 pixels and 25 fps
#define BEST_BIT_RATE_PER_PIXEL 38
#define WARST_BIT_RATE_PER_PIXEL 4

#define RED_COMPRESS_BUF_SIZE (1024 * 64)

typedef int64_t red_time_t;

static inline red_time_t timespec_to_red_time(struct timespec *time)
{
    return time->tv_sec * (1000 * 1000 * 1000) + time->tv_nsec;
}

#if defined(RED_WORKER_STAT) || defined(COMPRESS_STAT)
static clockid_t clock_id;

typedef unsigned long stat_time_t;

inline stat_time_t stat_now()
{
    struct timespec ts;
    clock_gettime(clock_id, &ts);
    return ts.tv_nsec + ts.tv_sec * 1000 * 1000 * 1000;
}

double stat_cpu_time_to_sec(stat_time_t time)
{
    return (double)time / (1000 * 1000 * 1000);
}

typedef struct stat_info_s {
    const char *name;
    uint32_t count;
    stat_time_t max;
    stat_time_t min;
    stat_time_t total;
#ifdef COMPRESS_STAT
    uint64_t orig_size;
    uint64_t comp_size;
#endif
} stat_info_t;

static inline void stat_reset(stat_info_t *info)
{
    info->count = info->max = info->total = 0;
    info->min = ~(stat_time_t)0;
#ifdef COMPRESS_STAT
    info->orig_size = info->comp_size = 0;
#endif
}

#endif

#ifdef RED_WORKER_STAT
static const char *add_stat_name = "add";
static const char *exclude_stat_name = "exclude";
static const char *__exclude_stat_name = "__exclude";

static inline void stat_init(stat_info_t *info, const char *name)
{
    info->name = name;
    stat_reset(info);
}

static inline void stat_add(stat_info_t *info, stat_time_t start)
{
    stat_time_t time;
    ++info->count;
    time = stat_now() - start;
    info->total += time;
    info->max = MAX(info->max, time);
    info->min = MIN(info->min, time);
}

#else
#define stat_add(a, b)
#define stat_init(a, b)
#endif

#ifdef COMPRESS_STAT
static const char *lz_stat_name = "lz";
static const char *glz_stat_name = "glz";
static const char *quic_stat_name = "quic";

static inline void stat_compress_init(stat_info_t *info, const char *name)
{
    info->name = name;
    stat_reset(info);
}

static inline void stat_compress_add(stat_info_t *info, stat_time_t start, int orig_size,
                                     int comp_size)
{
    stat_time_t time;
    ++info->count;
    time = stat_now() - start;
    info->total += time;
    info->max = MAX(info->max, time);
    info->min = MIN(info->min, time);
    info->orig_size += orig_size;
    info->comp_size += comp_size;
}

double inline stat_byte_to_mega(uint64_t size)
{
    return (double)size / (1000 * 1000);
}

#else
#define stat_compress_init(a, b)
#define stat_compress_add(a, b, c, d)
#endif

#define MAX_EPOLL_SOURCES 10
#define INF_EPOLL_WAIT ~0


typedef struct EventListener EventListener;
typedef void (*event_listener_action_proc)(EventListener *ctx, uint32_t events);
struct EventListener {
    uint32_t refs;
    event_listener_action_proc action;
};

enum {
    BUF_TYPE_RAW = 1,
    BUF_TYPE_COMPRESS_BUF,
    BUF_TYPE_CHUNK,
};

typedef struct BufDescriptor {
    uint32_t type;
    uint32_t size;
    uint8_t *data;
    uint32_t slot_id;
    uint32_t group_id;
} BufDescriptor;

enum {
    PIPE_ITEM_TYPE_DRAW,
    PIPE_ITEM_TYPE_MODE,
    PIPE_ITEM_TYPE_INVAL_ONE,
    PIPE_ITEM_TYPE_CURSOR,
    PIPE_ITEM_TYPE_MIGRATE,
    PIPE_ITEM_TYPE_LOCAL_CURSOR,
    PIPE_ITEM_TYPE_SET_ACK,
    PIPE_ITEM_TYPE_CURSOR_INIT,
    PIPE_ITEM_TYPE_IMAGE,
    PIPE_ITEM_TYPE_STREAM_CREATE,
    PIPE_ITEM_TYPE_STREAM_CLIP,
    PIPE_ITEM_TYPE_STREAM_DESTROY,
    PIPE_ITEM_TYPE_UPGRADE,
    PIPE_ITEM_TYPE_VERB,
    PIPE_ITEM_TYPE_MIGRATE_DATA,
    PIPE_ITEM_TYPE_PIXMAP_SYNC,
    PIPE_ITEM_TYPE_PIXMAP_RESET,
    PIPE_ITEM_TYPE_INVAL_CURSOR_CACHE,
    PIPE_ITEM_TYPE_INVAL_PALLET_CACHE,
};

typedef struct PipeItem {
    RingItem link;
    int type;
} PipeItem;

typedef struct VerbItem {
    PipeItem base;
    uint16_t verb;
} VerbItem;

#define MAX_CACHE_CLIENTS 4
#define MAX_LZ_ENCODERS MAX_CACHE_CLIENTS

typedef struct NewCacheItem NewCacheItem;

struct NewCacheItem {
    RingItem lru_link;
    NewCacheItem *next;
    uint64_t id;
    uint64_t sync[MAX_CACHE_CLIENTS];
    size_t size;
};

typedef struct CacheItem CacheItem;

struct CacheItem {
    union {
        PipeItem pipe_data;
        struct {
            RingItem lru_link;
            CacheItem *next;
        } cache_data;
    } u;
    uint64_t id;
    size_t size;
    uint32_t inval_type;
};

enum {
    CURSOR_TYPE_INVALID,
    CURSOR_TYPE_DEV,
    CURSOR_TYPE_LOCAL,
};

typedef struct CursorItem {
    PipeItem pipe_data;
    uint32_t group_id;
    int refs;
    int type;
    QXLCursorCmd *qxl_cursor;
} CursorItem;

typedef struct LocalCursor {
    CursorItem base;
    SpicePoint16 position;
    uint32_t data_size;
    SpiceCursor red_cursor;
} LocalCursor;

#define MAX_SEND_BUFS 20
#define MAX_BITMAPS 4
#define MAX_PIPE_SIZE 50
#define RECIVE_BUF_SIZE 1024

#define WIDE_CLIENT_ACK_WINDOW 40
#define NARROW_CLIENT_ACK_WINDOW 20

#define BITS_CACHE_HASH_SHIFT 10
#define BITS_CACHE_HASH_SIZE (1 << BITS_CACHE_HASH_SHIFT)
#define BITS_CACHE_HASH_MASK (BITS_CACHE_HASH_SIZE - 1)
#define BITS_CACHE_HASH_KEY(id) ((id) & BITS_CACHE_HASH_MASK)

#define CLIENT_CURSOR_CACHE_SIZE 256

#define CURSOR_CACHE_HASH_SHIFT 8
#define CURSOR_CACHE_HASH_SIZE (1 << CURSOR_CACHE_HASH_SHIFT)
#define CURSOR_CACHE_HASH_MASK (CURSOR_CACHE_HASH_SIZE - 1)
#define CURSOR_CACHE_HASH_KEY(id) ((id) & CURSOR_CACHE_HASH_MASK)

#define CLIENT_PALETTE_CACHE_SIZE 128

#define PALETTE_CACHE_HASH_SHIFT 8
#define PALETTE_CACHE_HASH_SIZE (1 << PALETTE_CACHE_HASH_SHIFT)
#define PALETTE_CACHE_HASH_MASK (PALETTE_CACHE_HASH_SIZE - 1)
#define PALETTE_CACHE_HASH_KEY(id) ((id) & PALETTE_CACHE_HASH_MASK)

typedef struct RedChannel RedChannel;
typedef void (*disconnect_channel_proc)(RedChannel *channel);
typedef void (*hold_item_proc)(void *item);
typedef void (*release_item_proc)(RedChannel *channel, void *item);
typedef int (*handle_message_proc)(RedChannel *channel, SpiceDataHeader *message);

struct RedChannel {
    EventListener listener;
    uint32_t id;
    struct RedWorker *worker;
    RedsStreamContext *peer;
    int migrate;

    Ring pipe;
    uint32_t pipe_size;

    uint32_t client_ack_window;
    uint32_t ack_generation;
    uint32_t client_ack_generation;
    uint32_t messages_window;

    struct {
        int blocked;
        SpiceDataHeader header;
        union {
            SpiceMsgSetAck ack;
        } u;
        uint32_t n_bufs;
        BufDescriptor bufs[MAX_SEND_BUFS];
        uint32_t size;
        uint32_t pos;
        void *item;
    } send_data;

    struct {
        uint8_t buf[RECIVE_BUF_SIZE];
        SpiceDataHeader *message;
        uint8_t *now;
        uint8_t *end;
    } recive_data;

    disconnect_channel_proc disconnect;
    hold_item_proc hold_item;
    release_item_proc release_item;
    handle_message_proc handle_message;
#ifdef RED_STATISTICS
    uint64_t *out_bytes_counter;
#endif
};

typedef struct ImageItem {
    PipeItem link;
    int refs;
    SpicePoint pos;
    int width;
    int height;
    int stride;
    int top_down;
    uint8_t data[0];
} ImageItem;

typedef struct Drawable Drawable;

typedef struct Stream Stream;
struct Stream {
    uint8_t refs;
    Drawable *current;
#ifdef STREAM_TRACE
    red_time_t last_time;
    int width;
    int height;
    SpiceRect dest_area;
#endif
    int top_down;
    Stream *next;
    RingItem link;
    AVCodecContext *av_ctx;
    AVFrame *av_frame;
    uint8_t* frame_buf;
    uint8_t* frame_buf_end;
    int bit_rate;
};

typedef struct StreamAgent {
    QRegion vis_region;
    PipeItem create_item;
    PipeItem destroy_item;
    Stream *stream;
    uint64_t lats_send_time;

    int frames;
    int drops;
    int fps;
} StreamAgent;

typedef struct StreamClipItem {
    PipeItem base;
    int refs;
    StreamAgent *stream_agent;
    int clip_type;
    QRegion region;
} StreamClipItem;

typedef struct RedCompressBuf RedCompressBuf;
struct RedCompressBuf {
    uint32_t buf[RED_COMPRESS_BUF_SIZE / 4];
    RedCompressBuf *next;
    RedCompressBuf *send_next;
};

static const int BITMAP_FMT_IS_PLT[] = {0, 1, 1, 1, 1, 1, 0, 0, 0, 0};
static const int BITMAP_FMT_IS_RGB[] = {0, 0, 0, 0, 0, 0, 1, 1, 1, 1};
static const int BITMAP_FMP_BYTES_PER_PIXEL[] = {0, 0, 0, 0, 0, 1, 2, 3, 4, 4};

typedef struct  __attribute__ ((__packed__)) RedImage {
    SpiceImageDescriptor descriptor;
    union { // variable length
        SpiceBitmap bitmap;
        SpiceQUICData quic;
        SpiceLZRGBData lz_rgb;
        SpiceLZPLTData lz_plt;
    };
} RedImage;

pthread_mutex_t cache_lock = PTHREAD_MUTEX_INITIALIZER;
Ring pixmap_cache_list = {&pixmap_cache_list, &pixmap_cache_list};

typedef struct PixmapCache PixmapCache;
struct PixmapCache {
    RingItem base;
    pthread_mutex_t lock;
    uint8_t id;
    uint32_t refs;
    NewCacheItem *hash_table[BITS_CACHE_HASH_SIZE];
    Ring lru;
    int64_t available;
    int64_t size;
    int32_t items;

    int freezed;
    RingItem *freezed_head;
    RingItem *freezed_tail;

    uint32_t generation;
    struct {
        uint8_t client;
        uint64_t message;
    } generation_initiator;
    uint64_t sync[MAX_CACHE_CLIENTS];
};

#define NUM_STREAMS 50

#define DISPLAY_MIGRATE_DATA_MAGIC (*(uint32_t*)"DMDA")
#define DISPLAY_MIGRATE_DATA_VERSION 2

typedef struct __attribute__ ((__packed__)) DisplayChannelMigrateData {
    //todo: add ack_generation + move common to generic migration data
    uint32_t magic;
    uint32_t version;
    uint64_t message_serial;

    uint8_t pixmap_cache_freezer;
    uint8_t pixmap_cache_id;
    int64_t pixmap_cache_size;
    uint64_t pixmap_cache_clients[MAX_CACHE_CLIENTS];

    uint8_t glz_dict_id;
    GlzEncDictRestoreData glz_dict_restore_data;
} DisplayChannelMigrateData;

typedef struct WaitForChannels {
    SpiceMsgWaitForChannels header;
    SpiceWaitForChannel buf[MAX_CACHE_CLIENTS];
} WaitForChannels;

typedef struct FreeList {
    int res_size;
    SpiceResorceList *res;
    uint64_t sync[MAX_CACHE_CLIENTS];
    WaitForChannels wait;
} FreeList;

typedef struct DisplayChannel DisplayChannel;

typedef void *(*enc_get_virt_fn_t)(void *get_virt_opaque, unsigned long addr, uint32_t add_size,
                                   uint32_t group_id);
typedef void (*enc_validate_virt_fn_t)(void *validate_virt_opaque, unsigned long virt,
                                       unsigned long from_addr, uint32_t add_size,
                                       uint32_t group_id);
typedef struct  {
    DisplayChannel *display_channel;
    RedCompressBuf *bufs_head;
    RedCompressBuf *bufs_tail;
    jmp_buf jmp_env;
    union {
        struct {
            SPICE_ADDRESS next;
            uint32_t stride;
            uint32_t group_id;

            void *enc_get_virt_opaque;
            enc_get_virt_fn_t enc_get_virt;
            void *enc_validate_virt_opaque;
            enc_validate_virt_fn_t enc_validate_virt;
        } lines_data;
        struct {
            uint8_t* next;
            int src_stride;
            uint32_t dest_stride;
            int lines;
            int max_lines_bunch;
            int input_bufs_pos;
            RedCompressBuf *input_bufs[2];
        } unstable_lines_data;
    } u;
    char message_buf[512];
} EncoderData;

typedef struct {
    QuicUsrContext usr;
    EncoderData data;
} QuicData;

typedef struct {
    LzUsrContext usr;
    EncoderData data;
} LzData;

typedef struct {
    GlzEncoderUsrContext usr;
    EncoderData data;
} GlzData;

/**********************************/
/* LZ dictionary related entities */
/**********************************/
#define MAX_GLZ_DRAWABLE_INSTANCES 2

typedef struct RedGlzDrawable RedGlzDrawable;

/* for each qxl drawable, there may be serveral instances of lz drawables */
typedef struct GlzDrawableInstanceItem {
    RingItem glz_link;
    RingItem free_link;
    GlzEncDictImageContext *glz_instance;
    RedGlzDrawable         *red_glz_drawable;
} GlzDrawableInstanceItem;

struct RedGlzDrawable {
    RingItem link;    // ordered by the time it was encoded
    QXLDrawable *qxl_drawable;
    Drawable    *drawable;
    uint32_t     group_id;
    uint8_t     *self_bitmap;
    GlzDrawableInstanceItem instances_pool[MAX_GLZ_DRAWABLE_INSTANCES];
    Ring instances;
    uint8_t instances_count;
    DisplayChannel *display_channel;
};

pthread_mutex_t glz_dictionary_list_lock = PTHREAD_MUTEX_INITIALIZER;
Ring glz_dictionary_list = {&glz_dictionary_list, &glz_dictionary_list};

typedef struct GlzSharedDictionary {
    RingItem base;
    GlzEncDictContext *dict;
    uint32_t refs;
    uint8_t id;
    pthread_rwlock_t encode_lock;
    int migrate_freeze;
} GlzSharedDictionary;

struct DisplayChannel {
    RedChannel base;

    int expect_init;
    int expect_migrate_mark;
    int expect_migrate_data;

    PixmapCache *pixmap_cache;
    uint32_t pixmap_cache_generation;
    int pending_pixmaps_sync;

    CacheItem *palette_cache[PALETTE_CACHE_HASH_SIZE];
    Ring palette_cache_lru;
    long palette_cache_available;
    uint32_t palette_cache_items;

    StreamAgent stream_agents[NUM_STREAMS];

    /* global lz encoding entities */
    GlzSharedDictionary *glz_dict;
    GlzEncoderContext   *glz;
    GlzData glz_data;

    Ring glz_drawables;               // all the living lz drawable, ordered by encoding time
    Ring glz_drawables_inst_to_free;               // list of instances to be freed
    pthread_mutex_t glz_drawables_inst_to_free_lock;

    struct {
        union {
            SpiceMsgDisplayDrawFill fill;
            SpiceMsgDisplayDrawOpaque opaque;
            SpiceMsgDisplayDrawCopy copy;
            SpiceMsgDisplayDrawTransparent transparent;
            SpiceMsgDisplayDrawAlphaBlend alpha_blend;
            SpiceMsgDisplayCopyBits copy_bits;
            SpiceMsgDisplayDrawBlend blend;
            SpiceMsgDisplayDrawRop3 rop3;
            SpiceMsgDisplayDrawBlackness blackness;
            SpiceMsgDisplayDrawWhiteness whiteness;
            SpiceMsgDisplayDrawInvers invers;
            SpiceMsgDisplayDrawStroke stroke;
            SpiceMsgDisplayDrawText text;
            SpiceMsgDisplayMode mode;
            SpiceMsgDisplayInvalOne inval_one;
            WaitForChannels wait;
            struct {
                SpiceMsgDisplayStreamCreate message;
                uint32_t num_rects;
            } stream_create;
            SpiceMsgDisplayStreamClip stream_clip;
            SpiceMsgDisplayStreamData stream_data;
            SpiceMsgDisplayStreamDestroy stream_destroy;
            SpiceMsgMigrate migrate;
            DisplayChannelMigrateData migrate_data;
        } u;

        uint32_t bitmap_pos;
        RedImage images[MAX_BITMAPS];

        uint32_t stream_outbuf_size;
        uint8_t *stream_outbuf; // caution stream buffer is also used as compress bufs!!!

        RedCompressBuf *free_compress_bufs;
        RedCompressBuf *used_compress_bufs;

        struct {
            SpiceSubMessageList sub_list;
            uint32_t sub_messages[DISPLAY_MAX_SUB_MESSAGES];
        } sub_list;
        SpicedSubMessage sub_header[DISPLAY_MAX_SUB_MESSAGES];

        FreeList free_list;
    } send_data;

#ifdef RED_STATISTICS
    StatNodeRef stat;
    uint64_t *cache_hits_counter;
    uint64_t *add_to_cache_counter;
    uint64_t *non_cache_counter;
#endif
#ifdef COMPRESS_STAT
    stat_info_t lz_stat;
    stat_info_t glz_stat;
    stat_info_t quic_stat;
#endif
};

typedef struct CursorChannel {
    RedChannel base;

    CacheItem *cursor_cache[CURSOR_CACHE_HASH_SIZE];
    Ring cursor_cache_lru;
    long cursor_cache_available;
    uint32_t cursor_cache_items;

    struct {
        union {
            SpiceMsgCursorInit cursor_init;
            SpiceMsgCursorSet cursor_set;
            SpiceMsgCursorMove cursor_move;
            SpiceMsgCursorTrail cursor_trail;
            SpiceMsgDisplayInvalOne inval_one;
            SpiceMsgMigrate migrate;
        } u;
    } send_data;
#ifdef RED_STATISTICS
    StatNodeRef stat;
#endif
} CursorChannel;

typedef struct __attribute__ ((__packed__)) LocalImage {
    QXLImage qxl_image;
    uint8_t buf[sizeof(QXLDataChunk *)]; // quic data area
} LocalImage;

typedef struct ImageCacheItem {
    RingItem lru_link;
    uint64_t id;
#ifdef IMAGE_CACHE_AGE
    uint32_t age;
#endif
    struct ImageCacheItem *next;
    cairo_surface_t *surf;
} ImageCacheItem;

#define IMAGE_CACHE_HASH_SIZE 1024

typedef struct ImageCache {
    ImageCacheItem *hash_table[IMAGE_CACHE_HASH_SIZE];
    Ring lru;
#ifdef IMAGE_CACHE_AGE
    uint32_t age;
#else
    uint32_t num_items;
#endif
} ImageCache;

enum {
    TREE_ITEM_TYPE_DRAWABLE,
    TREE_ITEM_TYPE_CONTAINER,
    TREE_ITEM_TYPE_SHADOW,
};

typedef struct TreeItem {
    RingItem siblings_link;
    uint32_t type;
    struct Container *container;
    QRegion rgn;
#ifdef PIPE_DEBUG
    uint32_t id;
#endif
} TreeItem;

#define IS_DRAW_ITEM(item) ((item)->type == TREE_ITEM_TYPE_DRAWABLE)

typedef struct Shadow {
    TreeItem base;
    QRegion on_hold;
    struct DrawItem* owner;
} Shadow;

typedef struct Container {
    TreeItem base;
    Ring items;
} Container;

typedef struct DrawItem {
    TreeItem base;
    uint8_t effect;
    uint8_t container_root;
    Shadow *shadow;
} DrawItem;

typedef enum {
    BITMAP_GRADUAL_INVALID,
    BITMAP_GRADUAL_NOT_AVAIL,
    BITMAP_GRADUAL_TRUE,
    BITMAP_GRADUAL_FALSE,
} BitmapGradualType;

struct Drawable {
    uint8_t refs;
    RingItem list_link;
    DrawItem tree_item;
    PipeItem pipe_item;
#ifdef UPDATE_AREA_BY_TREE
    RingItem collect_link;
#endif
    QXLDrawable *qxl_drawable;

    RedGlzDrawable *red_glz_drawable;

    red_time_t creation_time;
    int frames_count;
    int gradual_frames_count;
    int last_gradual_frame;
    Stream *stream;
#ifdef STREAM_TRACE
    int streamable;
#endif
    BitmapGradualType copy_bitmap_graduality;
    uint32_t group_id;
    uint8_t *self_bitmap;
};

typedef struct _Drawable _Drawable;
struct _Drawable {
    union {
        Drawable drawable;
        _Drawable *next;
    } u;
};

typedef struct _CursorItem _CursorItem;
struct _CursorItem {
    union {
        CursorItem cursor_item;
        _CursorItem *next;
    } u;
};

typedef struct UpgradeItem {
    PipeItem base;
    int refs;
    Drawable *drawable;
    QRegion region;
} UpgradeItem;

typedef void (*draw_fill_t)(void *canvas, SpiceRect *bbox, SpiceClip *clip, SpiceFill *fill);
typedef void (*draw_copy_t)(void *canvas, SpiceRect *bbox, SpiceClip *clip, SpiceCopy *copy);
typedef void (*draw_opaque_t)(void *canvas, SpiceRect *bbox, SpiceClip *clip, SpiceOpaque *opaque);
typedef void (*copy_bits_t)(void *canvas, SpiceRect *bbox, SpiceClip *clip, SpicePoint *src_pos);
typedef void (*draw_text_t)(void *canvas, SpiceRect *bbox, SpiceClip *clip, SpiceText *text);
typedef void (*draw_stroke_t)(void *canvas, SpiceRect *bbox, SpiceClip *clip, SpiceStroke *stroke);
typedef void (*draw_rop3_t)(void *canvas, SpiceRect *bbox, SpiceClip *clip, SpiceRop3 *rop3);
typedef void (*draw_blend_t)(void *canvas, SpiceRect *bbox, SpiceClip *clip, SpiceBlend *blend);
typedef void (*draw_blackness_t)(void *canvas, SpiceRect *bbox, SpiceClip *clip, SpiceBlackness *blackness);
typedef void (*draw_whiteness_t)(void *canvas, SpiceRect *bbox, SpiceClip *clip, SpiceWhiteness *whiteness);
typedef void (*draw_invers_t)(void *canvas, SpiceRect *bbox, SpiceClip *clip, SpiceInvers *invers);
typedef void (*draw_transparent_t)(void *canvas, SpiceRect *bbox, SpiceClip *clip, SpiceTransparent* transparent);
typedef void (*draw_alpha_blend_t)(void *canvas, SpiceRect *bbox, SpiceClip *clip, SpiceAlphaBlnd* alpha_blend);
typedef void (*read_pixels_t)(void *canvas, uint8_t *dest, int dest_stride, const SpiceRect *area);
typedef void (*set_top_mask_t)(void *canvas, int num_rect, const SpiceRect *rects);
typedef void (*clear_top_mask_t)(void *canvas);
typedef void (*validate_area_t)(void *canvas, int32_t stride, uint8_t *line_0, const SpiceRect *area);
typedef void (*destroy_t)(void *canvas);

typedef struct DrawFuncs {
    draw_fill_t draw_fill;
    draw_copy_t draw_copy;
    draw_opaque_t draw_opaque;
    copy_bits_t copy_bits;
    draw_text_t draw_text;
    draw_stroke_t draw_stroke;
    draw_rop3_t draw_rop3;
    draw_blend_t draw_blend;
    draw_blackness_t draw_blackness;
    draw_whiteness_t draw_whiteness;
    draw_invers_t draw_invers;
    draw_transparent_t draw_transparent;
    draw_alpha_blend_t draw_alpha_blend;
    read_pixels_t read_pixels;
    set_top_mask_t set_top_mask;
    clear_top_mask_t clear_top_mask;
    validate_area_t validate_area;
    destroy_t destroy;
} DrawFuncs;

typedef struct DrawContext {
    void *canvas;
    int top_down;
    uint32_t width;
    uint32_t height;
    int32_t stride;
    uint8_t depth;
    void *line_0;
} DrawContext;

typedef struct Surface {
    uint32_t refs;
    DrawContext context;
} Surface;

#ifdef STREAM_TRACE
typedef struct ItemTrace {
    red_time_t time;
    int frames_count;
    int gradual_frames_count;
    int last_gradual_frame;
    int width;
    int height;
    SpiceRect dest_area;
} ItemTrace;

#define TRACE_ITEMS_SHIFT 3
#define NUM_TRACE_ITEMS (1 << TRACE_ITEMS_SHIFT)
#define ITEMS_TRACE_MASK (NUM_TRACE_ITEMS - 1)

#endif

typedef struct MemSlot {
    int generation;
    unsigned long virt_start_addr;
    unsigned long virt_end_addr;
    long address_delta;
} MemSlot;

#define NUM_DRAWABLES 1000
#define NUM_CURSORS 100

typedef struct RedWorker {
    EventListener dev_listener;
    DisplayChannel *display_channel;
    CursorChannel *cursor_channel;
    QXLInterface *qxl;
    int id;
    int channel;
    int running;
    uint32_t *pending;
    int epoll;
    unsigned int epoll_timeout;
    uint32_t repoll_cmd_ring;
    uint32_t repoll_cursor_ring;
    uint32_t num_renderers;
    uint32_t renderers[RED_MAX_RENDERERS];
    uint32_t renderer;

    DrawFuncs draw_funcs;
    Surface surface;

    Ring current_list;
    Ring current;
    uint32_t current_size;
    uint32_t drawable_count;
    uint32_t transparent_count;

    uint32_t shadows_count;
    uint32_t containers_count;

    uint32_t bits_unique;

    CursorItem *cursor;
    int cursor_visible;
    SpicePoint16 cursor_position;
    uint16_t cursor_trail_length;
    uint16_t cursor_trail_frequency;

    _Drawable drawables[NUM_DRAWABLES];
    _Drawable *free_drawables;

    _CursorItem cursor_items[NUM_CURSORS];
    _CursorItem *free_cursor_items;

    MemSlot **mem_slots;
    uint32_t num_memslots_groups;
    uint32_t num_memslots;
    uint8_t mem_slot_bits;
    uint8_t generation_bits;
    uint8_t memslot_id_shift;
    uint8_t memslot_gen_shift;
    uint8_t internal_groupslot_id;
    unsigned long memslot_gen_mask;
    unsigned long memslot_clean_virt_mask;

    uint32_t preload_group_id;

    uint32_t local_images_pos;
    LocalImage local_images[MAX_BITMAPS];

    ImageCache image_cache;

    image_compression_t image_compression;

    uint32_t mouse_mode;

    uint32_t streaming_video;
    Stream streams_buf[NUM_STREAMS];
    Stream *free_streams;
    Ring streams;
#ifdef STREAM_TRACE
    ItemTrace items_trace[NUM_TRACE_ITEMS];
    uint32_t next_item_trace;
#endif

    QuicData quic_data;
    QuicContext *quic;

    LzData lz_data;
    LzContext  *lz;

#ifdef PIPE_DEBUG
    uint32_t last_id;
#endif
#ifdef RED_WORKER_STAT
    stat_info_t add_stat;
    stat_info_t exclude_stat;
    stat_info_t __exclude_stat;
    uint32_t add_count;
    uint32_t add_with_shadow_count;
#endif
#ifdef RED_STATISTICS
    StatNodeRef stat;
    uint64_t *wakeup_counter;
    uint64_t *command_counter;
#endif
} RedWorker;

pthread_mutex_t avcodec_lock = PTHREAD_MUTEX_INITIALIZER;

static void red_draw_qxl_drawable(RedWorker *worker, Drawable *drawable);
static void red_current_flush(RedWorker *worker);
static void display_channel_push(RedWorker *worker);
#ifdef DRAW_ALL
#define red_update_area(worker, rect)
#define red_draw_drawable(worker, item)
#else
static void red_draw_drawable(RedWorker *worker, Drawable *item);
static void red_update_area(RedWorker *worker, const SpiceRect *area);
#endif
static void red_release_cursor(RedWorker *worker, CursorItem *cursor);
static inline void release_drawable(RedWorker *worker, Drawable *item);
static void red_display_release_stream(DisplayChannel *display, StreamAgent *agent);
#ifdef STREAM_TRACE
static inline void red_detach_stream(RedWorker *worker, Stream *stream);
#endif
static void red_stop_stream(RedWorker *worker, Stream *stream);
static inline void red_stream_maintenance(RedWorker *worker, Drawable *candidate, Drawable *sect);
static inline void red_begin_send_massage(RedChannel *channel, void *item);
static inline void display_begin_send_massage(DisplayChannel *channel, void *item);
static void red_receive(RedChannel *channel);
static void red_release_pixmap_cache(DisplayChannel *channel);
static void red_release_glz(DisplayChannel *channel);
static void red_freeze_glz(DisplayChannel *channel);
static void display_channel_push_release(DisplayChannel *channel, uint8_t type, uint64_t id,
                                         uint64_t* sync_data);
static void red_display_release_stream_clip(DisplayChannel* channel, StreamClipItem *item);
static int red_display_free_some_independent_glz_drawables(DisplayChannel *channel);
static void red_display_free_glz_drawable(DisplayChannel *channel, RedGlzDrawable *drawable);
static void reset_rate(StreamAgent *stream_agent);
static int _bitmap_is_gradual(RedWorker *worker, SpiceBitmap *bitmap, uint32_t group_id);
static inline int _stride_is_extra(SpiceBitmap *bitmap);

#ifdef DUMP_BITMAP
static void dump_bitmap(RedWorker *worker, SpiceBitmap *bitmap, uint32_t group_id);
#endif

#ifdef COMPRESS_STAT
static void print_compress_stats(DisplayChannel *display_channel)
{
    if (!display_channel) {
        return;
    }
    red_printf("==> Compression stats for display %u", display_channel->base.id);
    red_printf("Method   \t  count  \torig_size(MB)\tenc_size(MB)\tenc_time(s)");
    red_printf("QUIC     \t%8d\t%13.2f\t%12.2f\t%12.2f",
               display_channel->quic_stat.count,
               stat_byte_to_mega(display_channel->quic_stat.orig_size),
               stat_byte_to_mega(display_channel->quic_stat.comp_size),
               stat_cpu_time_to_sec(display_channel->quic_stat.total)
               );
    red_printf("GLZ      \t%8d\t%13.2f\t%12.2f\t%12.2f",
               display_channel->glz_stat.count,
               stat_byte_to_mega(display_channel->glz_stat.orig_size),
               stat_byte_to_mega(display_channel->glz_stat.comp_size),
               stat_cpu_time_to_sec(display_channel->glz_stat.total)
               );
    red_printf("LZ       \t%8d\t%13.2f\t%12.2f\t%12.2f",
               display_channel->lz_stat.count,
               stat_byte_to_mega(display_channel->lz_stat.orig_size),
               stat_byte_to_mega(display_channel->lz_stat.comp_size),
               stat_cpu_time_to_sec(display_channel->lz_stat.total)
               );
    red_printf("-------------------------------------------------------------------");
    red_printf("Total    \t%8d\t%13.2f\t%12.2f\t%12.2f",
               display_channel->lz_stat.count + display_channel->glz_stat.count +
                                                display_channel->quic_stat.count,
               stat_byte_to_mega(display_channel->lz_stat.orig_size +
                                 display_channel->glz_stat.orig_size +
                                 display_channel->quic_stat.orig_size),
               stat_byte_to_mega(display_channel->lz_stat.comp_size +
                                 display_channel->glz_stat.comp_size +
                                 display_channel->quic_stat.comp_size),
               stat_cpu_time_to_sec(display_channel->lz_stat.total +
                                    display_channel->glz_stat.total +
                                    display_channel->quic_stat.total)
               );
}

#endif

static inline int get_memslot_id(RedWorker *worker, unsigned long addr)
{
    return addr >> worker->memslot_id_shift;
}

static inline int get_generation(RedWorker *worker, unsigned long addr)
{

    return (addr >> worker->memslot_gen_shift) & worker->memslot_gen_mask;
}

static inline unsigned long __get_clean_virt(RedWorker *worker, unsigned long addr)
{
    return addr & worker->memslot_clean_virt_mask;
}

static inline void print_memslots(RedWorker *worker)
{
    int i;
    int x;

    for (i = 0; i < worker->num_memslots_groups; ++i) {
        for (x = 0; x < worker->num_memslots; ++x) {
            if (!worker->mem_slots[i][x].virt_start_addr &&
                !worker->mem_slots[i][x].virt_end_addr) {
                continue;
            }
            printf("id %d, group %d, virt start %lx, virt end %lx, generation %u, delta %lx\n",
                   x, i, worker->mem_slots[i][x].virt_start_addr,
                   worker->mem_slots[i][x].virt_end_addr, worker->mem_slots[i][x].generation,
                   worker->mem_slots[i][x].address_delta);
            }
    }
}

static inline unsigned long get_virt_delta(RedWorker *worker, unsigned long addr, int group_id)
{
    MemSlot *slot;
    int slot_id;
    int generation;

    if (group_id > worker->num_memslots_groups) {
        PANIC("group_id %d too big", group_id);
    }

    slot_id = get_memslot_id(worker, addr);
    if (slot_id > worker->num_memslots) {
        PANIC("slod_id %d too big", slot_id);
    }

    slot = &worker->mem_slots[group_id][slot_id];

    generation = get_generation(worker, addr);
    if (generation != slot->generation) {
        PANIC("address generation is not valid");
    }

    return (slot->address_delta - (addr - __get_clean_virt(worker, addr)));
}

static inline void validate_virt(RedWorker *worker, unsigned long virt, int slot_id,
                                 uint32_t add_size, uint32_t group_id)
{
    MemSlot *slot;

    slot = &worker->mem_slots[group_id][slot_id];
    if ((virt + add_size) < virt) {
        PANIC("virtual address overlap");
    }

    if (virt < slot->virt_start_addr || (virt + add_size) > slot->virt_end_addr) {
        print_memslots(worker);
        PANIC("virtual address out of range 0x%lx 0x%lx %d %d 0x%lx 0x%lx 0x%lx", virt,
              slot->address_delta, slot_id, group_id, slot->virt_start_addr, slot->virt_end_addr,
              virt + add_size);
    }
}

static inline unsigned long get_virt(RedWorker *worker, unsigned long addr, uint32_t add_size,
                                     int group_id)
{
    int slot_id;
    int generation;
    unsigned long h_virt;

    MemSlot *slot;

    if (group_id > worker->num_memslots_groups) {
        PANIC("group_id too big");
    }

    slot_id = get_memslot_id(worker, addr);
    if (slot_id > worker->num_memslots) {
        PANIC("slot_id too big");
    }

    slot = &worker->mem_slots[group_id][slot_id];

    generation = get_generation(worker, addr);
    if (generation != slot->generation) {
        print_memslots(worker);
        PANIC("address generation is not valid, group_id %d, slot_id %d, gen %d, slot_gen %d\n",
              group_id, slot_id, generation, slot->generation);
    }

    h_virt = __get_clean_virt(worker, addr);
    h_virt += slot->address_delta;

    validate_virt(worker, h_virt, slot_id, add_size, group_id);

    return h_virt;
}

static void *cb_get_virt(void *opaque, unsigned long addr, uint32_t add_size, uint32_t group_id)
{
    return (void *)get_virt((RedWorker *)opaque, addr, add_size, group_id);
}

static void cb_validate_virt(void *opaque, unsigned long virt, unsigned long from_addr,
                             uint32_t add_size, uint32_t group_id)
{
    int slot_id = get_memslot_id((RedWorker *)opaque, from_addr);
    validate_virt((RedWorker *)opaque, virt, slot_id, add_size, group_id);
}

static void *cb_get_virt_preload_group(void *opaque, unsigned long addr, uint32_t add_size)
{
    return (void *)get_virt((RedWorker *)opaque, addr, add_size,
                            ((RedWorker *)opaque)->preload_group_id);
}

static void cb_validate_virt_preload_group(void *opaque, unsigned long virt,
                                           unsigned long from_addr, uint32_t add_size)
{
    int slot_id = get_memslot_id((RedWorker *)opaque, from_addr);
    validate_virt((RedWorker *)opaque, virt, slot_id, add_size,
                  ((RedWorker *)opaque)->preload_group_id);
}

char *draw_type_to_str(UINT8 type)
{
    switch (type) {
    case QXL_DRAW_FILL:
        return "QXL_DRAW_FILL";
    case QXL_DRAW_OPAQUE:
        return "QXL_DRAW_OPAQUE";
    case QXL_DRAW_COPY:
        return "QXL_DRAW_COPY";
    case QXL_DRAW_TRANSPARENT:
        return "QXL_DRAW_TRANSPARENT";
    case QXL_DRAW_ALPHA_BLEND:
        return "QXL_DRAW_ALPHA_BLEND";
    case QXL_COPY_BITS:
        return "QXL_COPY_BITS";
    case QXL_DRAW_BLEND:
        return "QXL_DRAW_BLEND";
    case QXL_DRAW_BLACKNESS:
        return "QXL_DRAW_BLACKNESS";
    case QXL_DRAW_WHITENESS:
        return "QXL_DRAW_WHITENESS";
    case QXL_DRAW_INVERS:
        return "QXL_DRAW_INVERS";
    case QXL_DRAW_ROP3:
        return "QXL_DRAW_ROP3";
    case QXL_DRAW_STROKE:
        return "QXL_DRAW_STROKE";
    case QXL_DRAW_TEXT:
        return "QXL_DRAW_TEXT";
    default:
        return "?";
    }
}

static void show_qxl_drawable(RedWorker *worker, QXLDrawable *drawable, const char *prefix)
{
    if (prefix) {
        printf("%s: ", prefix);
    }

    printf("%s effect %d bbox(%d %d %d %d)",
           draw_type_to_str(drawable->type),
           drawable->effect,
           drawable->bbox.top,
           drawable->bbox.left,
           drawable->bbox.bottom,
           drawable->bbox.right);

    switch (drawable->type) {
    case QXL_DRAW_FILL:
    case QXL_DRAW_OPAQUE:
    case QXL_DRAW_COPY:
    case QXL_DRAW_TRANSPARENT:
    case QXL_DRAW_ALPHA_BLEND:
    case QXL_COPY_BITS:
    case QXL_DRAW_BLEND:
    case QXL_DRAW_BLACKNESS:
    case QXL_DRAW_WHITENESS:
    case QXL_DRAW_INVERS:
    case QXL_DRAW_ROP3:
    case QXL_DRAW_STROKE:
    case QXL_DRAW_TEXT:
        break;
    default:
        red_error("bad rawable type");
    }
    printf("\n");
}

static void show_draw_item(RedWorker *worker, DrawItem *draw_item, const char *prefix)
{
    if (prefix) {
        printf("%s: ", prefix);
    }
    printf("effect %d bbox(%d %d %d %d)\n",
           draw_item->effect,
           draw_item->base.rgn.bbox.top,
           draw_item->base.rgn.bbox.left,
           draw_item->base.rgn.bbox.bottom,
           draw_item->base.rgn.bbox.right);
}

static inline void red_pipe_item_init(PipeItem *item, int type)
{
    ring_item_init(&item->link);
    item->type = type;
}

static inline void red_pipe_add(RedChannel *channel, PipeItem *item)
{
    ASSERT(channel);
    channel->pipe_size++;
    ring_add(&channel->pipe, &item->link);
}

static inline void red_pipe_add_after(RedChannel *channel, PipeItem *item, PipeItem *pos)
{
    ASSERT(channel && pos);
    channel->pipe_size++;
    ring_add_after(&item->link, &pos->link);
}

static inline int pipe_item_is_linked(PipeItem *item)
{
    return ring_item_is_linked(&item->link);
}

static inline void pipe_item_remove(PipeItem *item)
{
    ring_remove(&item->link);
}

static inline void red_pipe_add_tail(RedChannel *channel, PipeItem *item)
{
    ASSERT(channel);
    channel->pipe_size++;
    ring_add_before(&item->link, &channel->pipe);
}

static void red_pipe_add_verb(RedChannel* channel, uint16_t verb)
{
    VerbItem *item = malloc(sizeof(*item));
    if (!item) {
        PANIC("malloc failed");
    }
    red_pipe_item_init(&item->base, PIPE_ITEM_TYPE_VERB);
    item->verb = verb;
    red_pipe_add(channel, &item->base);
}

static void red_pipe_add_type(RedChannel* channel, int pipe_item_type)
{
    PipeItem *item = malloc(sizeof(*item));
    if (!item) {
        PANIC("malloc failed");
    }
    red_pipe_item_init(item, pipe_item_type);
    red_pipe_add(channel, item);
}

static inline void red_pipe_add_drawable(RedWorker *worker, Drawable *drawable)
{
    if (!worker->display_channel) {
        return;
    }
    drawable->refs++;
    red_pipe_add(&worker->display_channel->base, &drawable->pipe_item);
}

static inline void red_pipe_add_drawable_after(RedWorker *worker, Drawable *drawable,
                                               Drawable *pos_after)
{
    if (!worker->display_channel) {
        return;
    }

    if (!pos_after || !pipe_item_is_linked(&pos_after->pipe_item)) {
        red_pipe_add_drawable(worker, drawable);
        return;
    }
    drawable->refs++;
    red_pipe_add_after(&worker->display_channel->base, &drawable->pipe_item, &pos_after->pipe_item);
}

static inline void red_pipe_remove_drawable(RedWorker *worker, Drawable *drawable)
{
    if (ring_item_is_linked(&drawable->pipe_item.link)) {
        worker->display_channel->base.pipe_size--;
        ring_remove(&drawable->pipe_item.link);
        release_drawable(worker, drawable);
    }
}

static inline void red_pipe_add_image_item(RedWorker *worker, ImageItem *item)
{
    if (!worker->display_channel) {
        return;
    }
    item->refs++;
    red_pipe_add(&worker->display_channel->base, &item->link);
}

static inline uint64_t channel_message_serial(RedChannel *channel)
{
    return channel->send_data.header.serial;
}

static void release_image_item(ImageItem *item)
{
    if (!--item->refs) {
        free(item);
    }
}

static void release_upgrade_item(RedWorker* worker, UpgradeItem *item)
{
    if (!--item->refs) {
        release_drawable(worker, item->drawable);
        region_destroy(&item->region);
        free(item);
    }
}

static void red_pipe_clear(RedChannel *channel)
{
    PipeItem *item;

    ASSERT(channel);
    while ((item = (PipeItem *)ring_get_head(&channel->pipe))) {
        ring_remove(&item->link);
        switch (item->type) {
        case PIPE_ITEM_TYPE_DRAW:
            release_drawable(channel->worker, CONTAINEROF(item, Drawable, pipe_item));
            break;
        case PIPE_ITEM_TYPE_CURSOR:
            red_release_cursor(channel->worker, (CursorItem *)item);
            break;
        case PIPE_ITEM_TYPE_UPGRADE:
            release_upgrade_item(channel->worker, (UpgradeItem *)item);
            break;
        case PIPE_ITEM_TYPE_PIXMAP_RESET:
        case PIPE_ITEM_TYPE_PIXMAP_SYNC:
        case PIPE_ITEM_TYPE_INVAL_ONE:
        case PIPE_ITEM_TYPE_MODE:
        case PIPE_ITEM_TYPE_MIGRATE:
        case PIPE_ITEM_TYPE_SET_ACK:
        case PIPE_ITEM_TYPE_CURSOR_INIT:
        case PIPE_ITEM_TYPE_VERB:
        case PIPE_ITEM_TYPE_MIGRATE_DATA:
        case PIPE_ITEM_TYPE_INVAL_PALLET_CACHE:
        case PIPE_ITEM_TYPE_INVAL_CURSOR_CACHE:
            free(item);
            break;
        case PIPE_ITEM_TYPE_IMAGE:
            release_image_item((ImageItem *)item);
            break;
        case PIPE_ITEM_TYPE_STREAM_CREATE:
            red_display_release_stream((DisplayChannel *)channel,
                                       CONTAINEROF(item, StreamAgent, create_item));
            break;
        case PIPE_ITEM_TYPE_STREAM_CLIP:
            red_display_release_stream_clip((DisplayChannel *)channel, (StreamClipItem*)item);
            break;
        case PIPE_ITEM_TYPE_STREAM_DESTROY:
            red_display_release_stream((DisplayChannel *)channel,
                                       CONTAINEROF(item, StreamAgent, destroy_item));
            break;
        }
    }
    channel->pipe_size = 0;
}

#define CLIENT_PIXMAPS_CACHE
#include "red_client_shared_cache.h"
#undef CLIENT_PIXMAPS_CACHE

#define CLIENT_CURSOR_CACHE
#include "red_client_cache.h"
#undef CLIENT_CURSOR_CACHE

#define CLIENT_PALETTE_CACHE
#include "red_client_cache.h"
#undef CLIENT_PALETTE_CACHE

static void red_reset_palette_cache(DisplayChannel *display_channel)
{
    red_palette_cache_reset(display_channel, CLIENT_PALETTE_CACHE_SIZE);
}

static void red_reset_cursor_cache(CursorChannel *channel)
{
    red_cursor_cache_reset(channel, CLIENT_CURSOR_CACHE_SIZE);
}

static inline Drawable *alloc_drawable(RedWorker *worker)
{
    Drawable *drawable;
    if (!worker->free_drawables) {
        return NULL;
    }
    drawable = &worker->free_drawables->u.drawable;
    worker->free_drawables = worker->free_drawables->u.next;
    return drawable;
}

static inline void free_drawable(RedWorker *worker, Drawable *item)
{
    ((_Drawable *)item)->u.next = worker->free_drawables;
    worker->free_drawables = (_Drawable *)item;
}

static void drawables_init(RedWorker *worker)
{
    int i;

    worker->free_drawables = NULL;
    for (i = 0; i < NUM_DRAWABLES; i++) {
        free_drawable(worker, &worker->drawables[i].u.drawable);
    }
}


static void red_reset_stream_trace(RedWorker *worker);

static inline void __red_destroy_surface(RedWorker *worker)
{
    Surface *surface = &worker->surface;

    if (!--worker->surface.refs) {
#ifdef STREAM_TRACE
        red_reset_stream_trace(worker);
#endif
        worker->draw_funcs.destroy(surface->context.canvas);
        surface->context.canvas = NULL;
    }
}

static inline void red_destroy_surface(RedWorker *worker)
{
    Surface *surface = &worker->surface;

    PANIC_ON(!surface->context.canvas);
    __red_destroy_surface(worker);
}

static inline void free_qxl_drawable(RedWorker *worker, QXLDrawable *drawable, uint32_t group_id,
                                     uint8_t *self_bitmap)
{
    QXLReleaseInfoExt release_info_ext;
    red_destroy_surface(worker);

    if (self_bitmap) {
        free(self_bitmap);
    }
    release_info_ext.group_id = group_id;
    release_info_ext.info = &drawable->release_info;
    worker->qxl->release_resource(worker->qxl, release_info_ext);
}

static inline void release_drawable(RedWorker *worker, Drawable *item)
{
    if (!--item->refs) {
#ifdef STREAM_TRACE
        ASSERT(!item->stream);
#else
        if (item->stream) {
            red_stop_stream(worker, item->stream);
        }
#endif
        ASSERT(!item->tree_item.shadow);
        region_destroy(&item->tree_item.base.rgn);

        if (item->red_glz_drawable) {
            item->red_glz_drawable->drawable = NULL;
        } else { // no refernce to the qxl drawable left
            free_qxl_drawable(worker, item->qxl_drawable, item->group_id, item->self_bitmap);
        }
        free_drawable(worker, item);
    }
}

static inline void remove_shadow(RedWorker *worker, DrawItem *item)
{
    Shadow *shadow;

    if (!item->shadow) {
        return;
    }
    shadow = item->shadow;
    item->shadow = NULL;
    ring_remove(&shadow->base.siblings_link);
    region_destroy(&shadow->base.rgn);
    region_destroy(&shadow->on_hold);
    free(shadow);
    worker->shadows_count--;
}

static inline void current_remove_container(RedWorker *worker, Container *container)
{
    ASSERT(ring_is_empty(&container->items));
    worker->containers_count--;
    ring_remove(&container->base.siblings_link);
    region_destroy(&container->base.rgn);
    free(container);
}

static inline void container_cleanup(RedWorker *worker, Container *container)
{
    while (container && container->items.next == container->items.prev) {
        Container *next = container->base.container;
        if (container->items.next != &container->items) {
            TreeItem *item = (TreeItem *)ring_get_head(&container->items);
            ASSERT(item);
            ring_remove(&item->siblings_link);
            ring_add_after(&item->siblings_link, &container->base.siblings_link);
            item->container = container->base.container;
        }
        current_remove_container(worker, container);
        container = next;
    }
}

#ifdef STREAM_TRACE
static inline void red_add_item_trace(RedWorker *worker, Drawable *item)
{
    ItemTrace *trace;
    if (!item->streamable) {
        return;
    }

    trace = &worker->items_trace[worker->next_item_trace++ & ITEMS_TRACE_MASK];
    trace->time = item->creation_time;
    trace->frames_count = item->frames_count;
    trace->gradual_frames_count = item->gradual_frames_count;
    trace->last_gradual_frame = item->last_gradual_frame;
    SpiceRect* src_area = &item->qxl_drawable->u.copy.src_area;
    trace->width = src_area->right - src_area->left;
    trace->height = src_area->bottom - src_area->top;
    trace->dest_area = item->qxl_drawable->bbox;
}

#endif

static inline void current_remove_drawable(RedWorker *worker, Drawable *item)
{
    worker->drawable_count--;
    if (item->tree_item.effect != QXL_EFFECT_OPAQUE) {
        worker->transparent_count--;
    }
#ifdef STREAM_TRACE
    if (item->stream) {
        red_detach_stream(worker, item->stream);
    } else {
        red_add_item_trace(worker, item);
    }
#endif
    remove_shadow(worker, &item->tree_item);
    ring_remove(&item->tree_item.base.siblings_link);
    ring_remove(&item->list_link);
    release_drawable(worker, item);
    worker->current_size--;
}

static void remove_drawable(RedWorker *worker, Drawable *item)
{
    red_pipe_remove_drawable(worker, item);
    current_remove_drawable(worker, item);
}

static inline void current_remove(RedWorker *worker, TreeItem *item)
{
    TreeItem *now = item;

    for (;;) {
        Container *container = now->container;
        RingItem *ring_item;

        if (now->type == TREE_ITEM_TYPE_DRAWABLE) {
            ring_item = now->siblings_link.prev;
            remove_drawable(worker, CONTAINEROF(now, Drawable, tree_item));
        } else {
            Container *container = (Container *)now;

            ASSERT(now->type == TREE_ITEM_TYPE_CONTAINER);

            if ((ring_item = ring_get_head(&container->items))) {
                now = CONTAINEROF(ring_item, TreeItem, siblings_link);
                continue;
            }
            ring_item = now->siblings_link.prev;
            current_remove_container(worker, container);
        }
        if (now == item) {
            return;
        }

        if ((ring_item = ring_next(&container->items, ring_item))) {
            now = CONTAINEROF(ring_item, TreeItem, siblings_link);
        } else {
            now = (TreeItem *)container;
        }
    }
}

static void current_tree_for_each(RedWorker *worker, void (*f)(TreeItem *, void *), void * data)
{
    Ring *ring = &worker->current;
    RingItem *ring_item;
    Ring *top_ring;

    if (!(ring_item = ring_get_head(ring))) {
        return;
    }
    top_ring = ring;

    for (;;) {
        TreeItem *now = CONTAINEROF(ring_item, TreeItem, siblings_link);

        f(now, data);

        if (now->type == TREE_ITEM_TYPE_CONTAINER) {
            Container *container = (Container *)now;

            if ((ring_item = ring_get_head(&container->items))) {
                ring = &container->items;
                continue;
            }
        }
        for (;;) {
            ring_item = ring_next(ring, &now->siblings_link);
            if (ring_item) {
                break;
            }
            if (ring == top_ring) {
                return;
            }
            now = (TreeItem *)now->container;
            ring = (now->container) ? &now->container->items : top_ring;
        }
    }
}

static void red_current_clear(RedWorker *worker)
{
    RingItem *ring_item;

    while ((ring_item = ring_get_head(&worker->current))) {
        TreeItem *now = CONTAINEROF(ring_item, TreeItem, siblings_link);
        current_remove(worker, now);
    }
}

#ifdef PIPE_DEBUG

static void print_rgn(const char* prefix, const QRegion* rgn)
{
    int i;
    printf("TEST: %s: RGN: bbox %u %u %u %u\n",
           prefix,
           rgn->bbox.top,
           rgn->bbox.left,
           rgn->bbox.bottom,
           rgn->bbox.right);

    for (i = 0; i < rgn->num_rects; i++) {
        printf("TEST: %s: RECT %u %u %u %u\n",
               prefix,
               rgn->rects[i].top,
               rgn->rects[i].left,
               rgn->rects[i].bottom,
               rgn->rects[i].right);
    }
}

static void print_draw_item(const char* prefix, const DrawItem *draw_item)
{
    const TreeItem *base = &draw_item->base;
    const Drawable *drawable = CONTAINEROF(draw_item, Drawable, tree_item);
    printf("TEST: %s: draw id %u container %u effect %u",
           prefix,
           base->id, base->container ? base->container->base.id : 0,
           draw_item->effect);
    if (draw_item->shadow) {
        printf(" shadow %u\n", draw_item->shadow->base.id);
    } else {
        printf("\n");
    }
    print_rgn(prefix, &base->rgn);
}

static void print_shadow_item(const char* prefix, const Shadow *item)
{
    printf("TEST: %s: shadow %p id %d\n", prefix, item, item->base.id);
    print_rgn(prefix, &item->base.rgn);
}

static void print_container_item(const char* prefix, const Container *item)
{
    printf("TEST: %s: container %p id %d\n", prefix, item, item->base.id);
    print_rgn(prefix, &item->base.rgn);
}

static void print_base_item(const char* prefix, const TreeItem *base)
{
    switch (base->type) {
    case TREE_ITEM_TYPE_DRAWABLE:
        print_draw_item(prefix, (const DrawItem *)base);
        break;
    case TREE_ITEM_TYPE_SHADOW:
        print_shadow_item(prefix, (const Shadow *)base);
        break;
    case TREE_ITEM_TYPE_CONTAINER:
        print_container_item(prefix, (const Container *)base);
        break;
    default:
        red_error("invalid type %u", base->type);
    }
}

void __show_current(TreeItem *item, void *data)
{
    print_base_item("TREE", item);
}

static void show_current(RedWorker *worker)
{
    if (ring_is_empty(&worker->current)) {
        red_printf("TEST: TREE: EMPTY");
        return;
    }
    current_tree_for_each(worker, __show_current, NULL);
}

#else
#define print_rgn(a, b)
#define print_draw_private(a, b)
#define show_current(a)
#define print_shadow_item(a, b)
#define print_base_item(a, b)
#endif

static inline Shadow *__find_shadow(TreeItem *item)
{
    while (item->type == TREE_ITEM_TYPE_CONTAINER) {
        if (!(item = (TreeItem *)ring_get_tail(&((Container *)item)->items))) {
            return NULL;
        }
    }

    if (item->type != TREE_ITEM_TYPE_DRAWABLE) {
        return NULL;
    }

    return ((DrawItem *)item)->shadow;
}

static inline Ring *ring_of(RedWorker *worker, TreeItem *item)
{
    return (item->container) ? &item->container->items : &worker->current;
}

static inline int __contained_by(RedWorker *worker, TreeItem *item, Ring *ring)
{
    ASSERT(item && ring);
    do {
        Ring *now = ring_of(worker, item);
        if (now == ring) {
            return TRUE;
        }
    } while ((item = (TreeItem *)item->container));

    return FALSE;
}

static inline void __exclude_region(RedWorker *worker, TreeItem *item, QRegion *rgn,
                                    Ring **top_ring, Drawable *frame_candidate)
{
    QRegion and_rgn;
#ifdef RED_WORKER_STAT
    stat_time_t start_time = stat_now();
#endif

    region_clone(&and_rgn, rgn);
    region_and(&and_rgn, &item->rgn);
    if (!region_is_empty(&and_rgn)) {
        if (IS_DRAW_ITEM(item)) {
            DrawItem *draw = (DrawItem *)item;

            if (draw->effect == QXL_EFFECT_OPAQUE) {
                region_exclude(rgn, &and_rgn);
            }

            if (draw->shadow) {
                Shadow *shadow;
                int32_t x = item->rgn.bbox.left;
                int32_t y = item->rgn.bbox.top;

                region_exclude(&draw->base.rgn, &and_rgn);
                shadow = draw->shadow;
                region_offset(&and_rgn, shadow->base.rgn.bbox.left - x,
                              shadow->base.rgn.bbox.top - y);
                region_exclude(&shadow->base.rgn, &and_rgn);
                region_and(&and_rgn, &shadow->on_hold);
                if (!region_is_empty(&and_rgn)) {
                    region_exclude(&shadow->on_hold, &and_rgn);
                    region_or(rgn, &and_rgn);
                    // in flat representation of current, shadow is always his owner next
                    if (!__contained_by(worker, (TreeItem*)shadow, *top_ring)) {
                        *top_ring = ring_of(worker, (TreeItem*)shadow);
                    }
                }
            } else {
                if (frame_candidate) {
                    Drawable *drawable = CONTAINEROF(draw, Drawable, tree_item);
                    red_stream_maintenance(worker, frame_candidate, drawable);
                }
                region_exclude(&draw->base.rgn, &and_rgn);
            }
        } else if (item->type == TREE_ITEM_TYPE_CONTAINER) {
            region_exclude(&item->rgn, &and_rgn);

            if (region_is_empty(&item->rgn)) {  //assume container removal will follow
                Shadow *shadow;

                region_exclude(rgn, &and_rgn);
                if ((shadow = __find_shadow(item))) {
                    region_or(rgn, &shadow->on_hold);
                    if (!__contained_by(worker, (TreeItem*)shadow, *top_ring)) {
                        *top_ring = ring_of(worker, (TreeItem*)shadow);
                    }
                }
            }
        } else {
            Shadow *shadow;

            ASSERT(item->type == TREE_ITEM_TYPE_SHADOW);
            shadow = (Shadow *)item;
            region_exclude(rgn, &and_rgn);
            region_or(&shadow->on_hold, &and_rgn);
        }
    }
    region_destroy(&and_rgn);
    stat_add(&worker->__exclude_stat, start_time);
}

#ifdef USE_EXCLUDE_RGN

static void exclude_region(RedWorker *worker, Ring *ring, RingItem *ring_item, QRegion *rgn,
                           TreeItem **last, Drawable *frame_candidate)
{
#ifdef RED_WORKER_STAT
    stat_time_t start_time = stat_now();
#endif
    Ring *top_ring;

    if (!ring_item) {
        return;
    }

    top_ring = ring;

    for (;;) {
        TreeItem *now = CONTAINEROF(ring_item, TreeItem, siblings_link);
        Container *container = now->container;

        ASSERT(!region_is_empty(&now->rgn));

        if (region_intersects(rgn, &now->rgn)) {
            print_base_item("EXCLUDE2", now);
            __exclude_region(worker, now, rgn, &top_ring, frame_candidate);
            print_base_item("EXCLUDE3", now);

            if (region_is_empty(&now->rgn)) {
                ASSERT(now->type != TREE_ITEM_TYPE_SHADOW);
                ring_item = now->siblings_link.prev;
                print_base_item("EXCLUDE_REMOVE", now);
                current_remove(worker, now);
                if (last && *last == now) {
                    *last = (TreeItem *)ring_next(ring, ring_item);
                }
            } else if (now->type == TREE_ITEM_TYPE_CONTAINER) {
                Container *container = (Container *)now;
                if ((ring_item = ring_get_head(&container->items))) {
                    ring = &container->items;
                    ASSERT(((TreeItem *)ring_item)->container);
                    continue;
                }
                ring_item = &now->siblings_link;
            }

            if (region_is_empty(rgn)) {
                stat_add(&worker->exclude_stat, start_time);
                return;
            }
        }

        while ((last && *last == (TreeItem *)ring_item) ||
               !(ring_item = ring_next(ring, ring_item))) {
            if (ring == top_ring) {
                stat_add(&worker->exclude_stat, start_time);
                return;
            }
            ring_item = &container->base.siblings_link;
            container = container->base.container;
            ring = (container) ? &container->items : top_ring;
        }
    }
}

#else

static void exclude_region(RedWorker *worker, Ring *ring, RingItem *ring_item, QRegion *rgn)
{
#ifdef RED_WORKER_STAT
    stat_time_t start_time = stat_now();
#endif
    Ring *top_ring;

    if (!ring_item) {
        return;
    }

    top_ring = ring;

    for (;;) {
        TreeItem *now = CONTAINEROF(ring_item, TreeItem, siblings_link);
        Container *container = now->container;

        ASSERT(!region_is_empty(&now->rgn));

        if (region_test(rgn, &now->rgn, REGION_TEST_SHARED)) {
            print_base_item("EXCLUDE2", now);
            __exclude_region(worker, now, rgn, &top_ring);
            print_base_item("EXCLUDE3", now);

            if (region_is_empty(&now->rgn)) {
                ASSERT(now->type != TREE_ITEM_TYPE_SHADOW);
                ring_item = now->siblings_link.prev;
                print_base_item("EXCLUDE_REMOVE", now);
                current_remove(worker, now);
            } else if (now->type == TREE_ITEM_TYPE_CONTAINER) {
                Container *container = (Container *)now;
                if ((ring_item = ring_get_head(&container->items))) {
                    ring = &container->items;
                    ASSERT(((TreeItem *)ring_item)->container);
                    continue;
                }
                ring_item = &now->siblings_link;
            }

            if (region_is_empty(rgn)) {
                stat_add(&worker->exclude_stat, start_time);
                return;
            }
        }

        while (!(ring_item = ring_next(ring, ring_item))) {
            if (ring == top_ring) {
                stat_add(&worker->exclude_stat, start_time);
                return;
            }
            ring_item = &container->base.siblings_link;
            container = container->base.container;
            ring = (container) ? &container->items : top_ring;
        }
    }
}

#endif

static inline Container *__new_container(RedWorker *worker, DrawItem *item)
{
    Container *container = malloc(sizeof(Container));
    if (!container) {
        return NULL;
    }
    worker->containers_count++;
#ifdef PIPE_DEBUG
    container->base.id = ++worker->last_id;
#endif
    container->base.type = TREE_ITEM_TYPE_CONTAINER;
    container->base.container = item->base.container;
    item->base.container = container;
    item->container_root = TRUE;
    region_clone(&container->base.rgn, &item->base.rgn);
    ring_item_init(&container->base.siblings_link);
    ring_add_after(&container->base.siblings_link, &item->base.siblings_link);
    ring_remove(&item->base.siblings_link);
    ring_init(&container->items);
    ring_add(&container->items, &item->base.siblings_link);

    return container;
}

static inline int is_opaque_item(TreeItem *item)
{
    return item->type == TREE_ITEM_TYPE_CONTAINER ||
           (IS_DRAW_ITEM(item) && ((DrawItem *)item)->effect == QXL_EFFECT_OPAQUE);
}

static inline void __current_add_drawable(RedWorker *worker, Drawable *drawable, RingItem *pos)
{
    ring_add_after(&drawable->tree_item.base.siblings_link, pos);
    ring_add(&worker->current_list, &drawable->list_link);
    drawable->refs++;
}

#ifdef USE_EXCLUDE_RGN

static int is_equal_path(RedWorker *worker, SPICE_ADDRESS p1, SPICE_ADDRESS p2, uint32_t group_id1,
                         uint32_t group_id2)
{
    QXLPath *path1;
    QXLPath *path2;
    QXLDataChunk *chunk1;
    QXLDataChunk *chunk2;
    uint8_t *data1;
    uint8_t *data2;
    int size;
    int size1;
    int size2;

    ASSERT(p1 && p2);

    path1 = (QXLPath *)get_virt(worker, p1, sizeof(QXLPath), group_id1);
    path2 = (QXLPath *)get_virt(worker, p2, sizeof(QXLPath), group_id2);

    if ((size = path1->data_size) != path2->data_size) {
        return FALSE;
    }
    ASSERT(size);

    chunk1 = &path1->chunk;
    size1 = chunk1->data_size;
    data1 = chunk1->data;

    chunk2 = &path2->chunk;
    size2 = chunk2->data_size;
    data2 = chunk2->data;

    for (;;) {
        int now = MIN(size1, size2);
        ASSERT(now);
        if (memcmp(data1, data2, now)) {
            return FALSE;
        }
        if (!(size -= now)) {
            return TRUE;
        }
        if ((size1 -= now) == 0) {
            ASSERT(chunk1->next_chunk)
            chunk1 = (QXLDataChunk *)get_virt(worker, chunk1->next_chunk, sizeof(QXLDataChunk),
                                              group_id1);
            size1 = chunk1->data_size;
            data1 = chunk1->data;
        } else {
            data1 += now;
        }

        if ((size2 -= now) == 0) {
            ASSERT(chunk2->next_chunk)
            chunk2 = (QXLDataChunk *)get_virt(worker, chunk2->next_chunk, sizeof(QXLDataChunk),
                                              group_id2);
            size2 = chunk2->data_size;
            data2 = chunk2->data;
        } else {
            data2 += now;
        }
    }
}

// partial imp
static int is_equal_brush(SpiceBrush *b1, SpiceBrush *b2)
{
    return b1->type == b2->type && b1->type == SPICE_BRUSH_TYPE_SOLID && b1->u.color == b1->u.color;
}

// partial imp
static int is_equal_line_attr(SpiceLineAttr *a1, SpiceLineAttr *a2)
{
    return a1->flags == a2->flags && a1->join_style == a2->join_style &&
           a1->end_style == a2->end_style && a1->style_nseg == a2->style_nseg &&
           a1->width == a2->width && a1->miter_limit == a2->miter_limit &&
           a1->style_nseg == 0;
}

static inline int rect_is_equal(const SpiceRect *r1, const SpiceRect *r2)
{
    return r1->top == r2->top && r1->left == r2->left &&
           r1->bottom == r2->bottom && r1->right == r2->right;
}

// partial imp
static int is_same_geometry(RedWorker *worker, Drawable *d1, Drawable *d2)
{
    if (d1->qxl_drawable->type != d2->qxl_drawable->type) {
        return FALSE;
    }

    switch (d1->qxl_drawable->type) {
    case QXL_DRAW_STROKE:
        return is_equal_line_attr(&d1->qxl_drawable->u.stroke.attr,
                                  &d2->qxl_drawable->u.stroke.attr) &&
               is_equal_path(worker, d1->qxl_drawable->u.stroke.path,
                             d2->qxl_drawable->u.stroke.path, d1->group_id,
                             d2->group_id);
    case QXL_DRAW_FILL:
        return rect_is_equal(&d1->qxl_drawable->bbox, &d2->qxl_drawable->bbox);
    default:
        return FALSE;
    }
}

static int is_same_drawable(RedWorker *worker, Drawable *d1, Drawable *d2)
{
    if (!is_same_geometry(worker, d1, d2)) {
        return FALSE;
    }

    switch (d1->qxl_drawable->type) {
    case QXL_DRAW_STROKE:
        return is_equal_brush(&d1->qxl_drawable->u.stroke.brush, &d2->qxl_drawable->u.stroke.brush);
    case QXL_DRAW_FILL:
        return is_equal_brush(&d1->qxl_drawable->u.fill.brush, &d2->qxl_drawable->u.fill.brush);
    default:
        return FALSE;
    }
}

static inline void red_free_stream(RedWorker *worker, Stream *stream)
{
    stream->next = worker->free_streams;
    worker->free_streams = stream;
}

static void red_release_stream(RedWorker *worker, Stream *stream)
{
    if (!--stream->refs) {
#ifdef STREAM_TRACE
        ASSERT(!ring_item_is_linked(&stream->link));
#else
        ring_remove(&stream->link);
#endif
        pthread_mutex_lock(&avcodec_lock);
        avcodec_close(stream->av_ctx);
        pthread_mutex_unlock(&avcodec_lock);
        av_free(stream->av_ctx);
        av_free(stream->av_frame);
        free(stream->frame_buf);
        red_free_stream(worker, stream);
    }
}

#ifdef STREAM_TRACE
static inline void red_detach_stream(RedWorker *worker, Stream *stream)
{
    ASSERT(stream->current && stream->current->stream);
    ASSERT(stream->current->stream == stream);
    stream->current->stream = NULL;
    stream->current = NULL;
}

static StreamClipItem *__new_stream_clip(DisplayChannel* channel, StreamAgent *agent)
{
    StreamClipItem *item = (StreamClipItem *)malloc(sizeof(*item));
    if (!item) {
        PANIC("alloc failed");
    }
    red_pipe_item_init((PipeItem *)item, PIPE_ITEM_TYPE_STREAM_CLIP);

    item->stream_agent = agent;
    agent->stream->refs++;
    item->refs = 1;
    return item;
}

static void push_stream_clip_by_drawable(DisplayChannel* channel, StreamAgent *agent,
                                         Drawable *drawable)
{
    StreamClipItem *item = __new_stream_clip(channel, agent);
    if (!item) {
        PANIC("alloc failed");
    }

    if (drawable->qxl_drawable->clip.type == SPICE_CLIP_TYPE_NONE) {
        region_init(&item->region);
        item->clip_type = SPICE_CLIP_TYPE_NONE;
    } else {
        item->clip_type = SPICE_CLIP_TYPE_RECTS;
        region_clone(&item->region, &drawable->tree_item.base.rgn);
    }
    red_pipe_add((RedChannel*)channel, (PipeItem *)item);
}

static void push_stream_clip(DisplayChannel* channel, StreamAgent *agent)
{
    StreamClipItem *item = __new_stream_clip(channel, agent);
    if (!item) {
        PANIC("alloc failed");
    }
    item->clip_type = SPICE_CLIP_TYPE_RECTS;
    region_clone(&item->region, &agent->vis_region);
    red_pipe_add((RedChannel*)channel, (PipeItem *)item);
}

static void red_display_release_stream_clip(DisplayChannel* channel, StreamClipItem *item)
{
    if (!--item->refs) {
        red_display_release_stream(channel, item->stream_agent);
        region_destroy(&item->region);
        free(item);
    }
}

static void red_attach_stream(RedWorker *worker, Drawable *drawable, Stream *stream)
{
    DisplayChannel *channel;
    ASSERT(!drawable->stream && !stream->current);
    ASSERT(drawable && stream);
    stream->current = drawable;
    drawable->stream = stream;
    stream->last_time = drawable->creation_time;

    if ((channel = worker->display_channel)) {
        StreamAgent *agent = &channel->stream_agents[stream - worker->streams_buf];
        if (!region_is_equal(&agent->vis_region, &drawable->tree_item.base.rgn)) {
            region_destroy(&agent->vis_region);
            region_clone(&agent->vis_region, &drawable->tree_item.base.rgn);
            push_stream_clip_by_drawable(channel, agent, drawable);
        }
    }
}

#endif

static void red_stop_stream(RedWorker *worker, Stream *stream)
{
    DisplayChannel *channel;
#ifdef STREAM_TRACE
    ASSERT(ring_item_is_linked(&stream->link));
    ASSERT(!stream->current);
#else
    ASSERT(stream->current && stream->current->stream);
    stream->current->stream = NULL;
    stream->current = NULL;
#endif

    if ((channel = worker->display_channel)) {
        StreamAgent *stream_agent;
        stream_agent = &channel->stream_agents[stream - worker->streams_buf];
        region_clear(&stream_agent->vis_region);
        ASSERT(!pipe_item_is_linked(&stream_agent->destroy_item));
        stream->refs++;
        red_pipe_add(&channel->base, &stream_agent->destroy_item);
    }
#ifdef STREAM_TRACE
    ring_remove(&stream->link);
#endif
    red_release_stream(worker, stream);
}

#ifdef STREAM_TRACE
static inline void red_detach_stream_gracefully(RedWorker *worker, Stream *stream)
{
    DisplayChannel *channel;
    ASSERT(stream->current);

    if ((channel = worker->display_channel) && !pipe_item_is_linked(&stream->current->pipe_item)) {
        UpgradeItem *upgrade_item;

        if (!(upgrade_item = (UpgradeItem *)malloc(sizeof(*upgrade_item)))) {
            PANIC("malloc failed");
        }
        upgrade_item->refs = 1;
        red_pipe_item_init(&upgrade_item->base, PIPE_ITEM_TYPE_UPGRADE);
        upgrade_item->drawable = stream->current;
        upgrade_item->drawable->refs++;
        region_clone(&upgrade_item->region, &upgrade_item->drawable->tree_item.base.rgn);
        red_pipe_add((RedChannel *)channel, &upgrade_item->base);
    }
    red_detach_stream(worker, stream);
}

#else
static inline void red_stop_stream_gracefully(RedWorker *worker, Stream *stream)
{
    ASSERT(stream->current);
    if (worker->display_channel && !pipe_item_is_linked(&stream->current->pipe_item)) {
        UpgradeItem *item;
        if ((item = (UpgradeItem *)malloc(sizeof(*item)))) {
            item->refs = 1;
            red_pipe_item_init(&item->base, PIPE_ITEM_TYPE_UPGRADE);
            item->drawable = stream->current;
            item->drawable->refs++;
            region_clone(&item->region, &item->drawable->tree_item.base.rgn);
            red_pipe_add((RedChannel *)worker->display_channel, &item->base);
        }
    }
    red_stop_stream(worker, stream);
}

#endif

#ifdef STREAM_TRACE
static void red_detach_streams_behind(RedWorker *worker, QRegion *region)
{
    Ring *ring = &worker->streams;
    RingItem *item = ring_get_head(ring);
    DisplayChannel *channel = worker->display_channel;

    while (item) {
        Stream *stream = CONTAINEROF(item, Stream, link);
        item = ring_next(ring, item);

        if (channel) {
            StreamAgent *agent = &channel->stream_agents[stream - worker->streams_buf];
            if (region_intersects(&agent->vis_region, region)) {
                region_clear(&agent->vis_region);
                push_stream_clip(channel, agent);
                if (stream->current) {
                    red_detach_stream_gracefully(worker, stream);
                }
            }
        } else if (stream->current && region_intersects(&stream->current->tree_item.base.rgn,
                                                        region)) {
            red_detach_stream(worker, stream);
        }
    }
}

#else
static void red_stop_streams_behind(RedWorker *worker, QRegion *region)
{
    Ring *ring = &worker->streams;
    RingItem *item = ring_get_head(ring);

    while (item) {
        Stream *stream = CONTAINEROF(item, Stream, link);
        stream->refs++;
        if (stream->current && region_intersects(region, &stream->current->tree_item.base.rgn)) {
            red_stop_stream_gracefully(worker, stream);
        }
        item = ring_next(ring, item);
        red_release_stream(worker, stream);
    }
}

#endif

static void red_streams_update_clip(RedWorker *worker, Drawable *drawable)
{
    DisplayChannel *channel;
    Ring *ring;
    RingItem *item;

    if (!(channel = worker->display_channel)) {
        return;
    }

    ring = &worker->streams;
    item = ring_get_head(ring);

    while (item) {
        Stream *stream = CONTAINEROF(item, Stream, link);
        StreamAgent *agent;

        item = ring_next(ring, item);

        agent = &channel->stream_agents[stream - worker->streams_buf];

        if (stream->current == drawable) {
            continue;
        }

        if (region_intersects(&agent->vis_region, &drawable->tree_item.base.rgn)) {
            region_exclude(&agent->vis_region, &drawable->tree_item.base.rgn);
            push_stream_clip(channel, agent);
        }
    }
}

static inline unsigned int red_get_streams_timout(RedWorker *worker)
{
    unsigned int timout = -1;
    Ring *ring = &worker->streams;
    RingItem *item = ring;
    struct timespec time;

    clock_gettime(CLOCK_MONOTONIC, &time);
    red_time_t now = timespec_to_red_time(&time);
    while ((item = ring_next(ring, item))) {
        Stream *stream;

        stream = CONTAINEROF(item, Stream, link);
#ifdef STREAM_TRACE
        red_time_t delta = (stream->last_time + RED_STREAM_TIMOUT) - now;

        if (delta < 1000 * 1000) {
            return 0;
        }
        timout = MIN(timout, (unsigned int)(delta / (1000 * 1000)));
#else
        if (stream->current) {
            red_time_t delta = (stream->current->creation_time + RED_STREAM_TIMOUT) - now;
            if (delta < 1000 * 1000) {
                return 0;
            }
            timout = MIN(timout, (unsigned int)(delta / (1000 * 1000)));
        }
#endif
    }
    return timout;
}

static inline void red_handle_streams_timout(RedWorker *worker)
{
    Ring *ring = &worker->streams;
    struct timespec time;
    RingItem *item;

    clock_gettime(CLOCK_MONOTONIC, &time);
    red_time_t now = timespec_to_red_time(&time);
    item = ring_get_head(ring);
    while (item) {
        Stream *stream = CONTAINEROF(item, Stream, link);
#ifdef STREAM_TRACE
        item = ring_next(ring, item);
        if (now >= (stream->last_time + RED_STREAM_TIMOUT)) {
            if (stream->current) {
                red_detach_stream_gracefully(worker, stream);
            }
            red_stop_stream(worker, stream);
        }
#else
        stream->refs++;
        if (stream->current && now >= (stream->current->creation_time + RED_STREAM_TIMOUT)) {
            red_stop_stream_gracefully(worker, stream);
        }
        item = ring_next(ring, item);
        red_release_stream(worker, stream);
#endif
    }
}

static void red_display_release_stream(DisplayChannel *display, StreamAgent *agent)
{
    ASSERT(agent->stream);
    red_release_stream(display->base.worker, agent->stream);
}

static inline Stream *red_alloc_stream(RedWorker *worker)
{
    Stream *stream;
    if (!worker->free_streams) {
        return NULL;
    }
    stream = worker->free_streams;
    worker->free_streams = worker->free_streams->next;
    return stream;
}

static int get_bit_rate(int width, int height)
{
    uint64_t bit_rate = width * height * BEST_BIT_RATE_PER_PIXEL;
    if (IS_LOW_BANDWIDTH()) {
        bit_rate = MIN(bitrate_per_sec * 70 / 100, bit_rate);
        bit_rate = MAX(bit_rate, width * height * WARST_BIT_RATE_PER_PIXEL);
    }
    return bit_rate;
}

static void red_dispaly_create_stream(DisplayChannel *display, Stream *stream)
{
    StreamAgent *agent = &display->stream_agents[stream - display->base.worker->streams_buf];
    stream->refs++;
    ASSERT(region_is_empty(&agent->vis_region));
    if (stream->current) {
        agent->frames = 1;
        region_clone(&agent->vis_region, &stream->current->tree_item.base.rgn);
    } else {
        agent->frames = 0;
    }
    agent->drops = 0;
    agent->fps = MAX_FPS;
    reset_rate(agent);
    red_pipe_add(&display->base, &agent->create_item);
}

static AVCodecContext *red_init_video_encoder(int width, int height)
{
    AVCodec *codec;
    AVCodecContext *ctx;
    int r;

    codec = avcodec_find_encoder(CODEC_ID_MJPEG);

    if (!codec) {
        red_printf("codec not found");
        return NULL;
    }

    if (!(ctx = avcodec_alloc_context())) {
        red_printf("alloc ctx failed");
        return NULL;
    }
    ctx->bit_rate = get_bit_rate(width, height);
    ASSERT(width % 2 == 0);
    ASSERT(height % 2 == 0);
    ctx->width = width;
    ctx->height = height;
    ctx->time_base = (AVRational){1, MAX_FPS};
    ctx->gop_size = 10;
    ctx->max_b_frames = 0;
    ctx->pix_fmt = PIX_FMT_YUVJ420P;

    pthread_mutex_lock(&avcodec_lock);
    r = avcodec_open(ctx, codec);
    pthread_mutex_unlock(&avcodec_lock);
    if (r < 0) {
        red_printf("avcodec open failed");
        av_free(ctx);
        return NULL;
    }
    return ctx;
}

static void red_create_stream(RedWorker *worker, Drawable *drawable)
{
    AVCodecContext *av_ctx;
    Stream *stream;
    AVFrame *frame;
    uint8_t* frame_buf;
    SpiceRect* src_rect;
    int stream_width;
    int stream_height;
    int pict_size;

    ASSERT(!drawable->stream);

    if (!(stream = red_alloc_stream(worker))) {
        return;
    }

    ASSERT(drawable->qxl_drawable->type == QXL_DRAW_COPY);
    src_rect = &drawable->qxl_drawable->u.copy.src_area;
    stream_width = ALIGN(src_rect->right - src_rect->left, 2);
    stream_height = ALIGN(src_rect->bottom - src_rect->top, 2);

    if (!(av_ctx = red_init_video_encoder(stream_width, stream_height))) {
        goto error_1;
    }

    if (!(frame = avcodec_alloc_frame())) {
        goto error_2;
    }

    if ((pict_size = avpicture_get_size(av_ctx->pix_fmt, stream_width, stream_height)) < 0) {
        goto error_3;
    }

    if (!(frame_buf = malloc(pict_size))) {
        goto error_3;
    }

    if (avpicture_fill((AVPicture *)frame, frame_buf, av_ctx->pix_fmt, stream_width,
                       stream_height) < 0) {
        goto error_4;
    }

    ring_add(&worker->streams, &stream->link);
    stream->current = drawable;
#ifdef STREAM_TRACE
    stream->last_time = drawable->creation_time;
    stream->width = src_rect->right - src_rect->left;
    stream->height = src_rect->bottom - src_rect->top;
    stream->dest_area = drawable->qxl_drawable->bbox;
#endif
    stream->refs = 1;
    stream->av_ctx = av_ctx;
    stream->bit_rate = av_ctx->bit_rate;
    stream->av_frame = frame;
    stream->frame_buf = frame_buf;
    stream->frame_buf_end = frame_buf + pict_size;
    QXLImage *qxl_image = (QXLImage *)get_virt(worker, drawable->qxl_drawable->u.copy.src_bitmap,
                                               sizeof(QXLImage), drawable->group_id);
    stream->top_down = !!(qxl_image->bitmap.flags & SPICE_BITMAP_FLAGS_TOP_DOWN);
    drawable->stream = stream;

    if (worker->display_channel) {
        red_dispaly_create_stream(worker->display_channel, stream);
    }

    return;

error_4:
    free(frame_buf);

error_3:
    av_free(frame);

error_2:
    pthread_mutex_lock(&avcodec_lock);
    avcodec_close(av_ctx);
    pthread_mutex_unlock(&avcodec_lock);
    av_free(av_ctx);

error_1:
    red_free_stream(worker, stream);
}

static void red_disply_start_streams(DisplayChannel *display_channel)
{
    Ring *ring = &display_channel->base.worker->streams;
    RingItem *item = ring;

    while ((item = ring_next(ring, item))) {
        Stream *stream = CONTAINEROF(item, Stream, link);
        red_dispaly_create_stream(display_channel, stream);
    }
}

static void red_display_init_streams(DisplayChannel *display)
{
    int i;
    for (i = 0; i < NUM_STREAMS; i++) {
        StreamAgent *agent = &display->stream_agents[i];
        agent->stream = &display->base.worker->streams_buf[i];
        region_init(&agent->vis_region);
        red_pipe_item_init(&agent->create_item, PIPE_ITEM_TYPE_STREAM_CREATE);
        red_pipe_item_init(&agent->destroy_item, PIPE_ITEM_TYPE_STREAM_DESTROY);
    }
}

static void red_display_destroy_streams(DisplayChannel *display)
{
    int i;
    for (i = 0; i < NUM_STREAMS; i++) {
        StreamAgent *agent = &display->stream_agents[i];
        region_destroy(&agent->vis_region);
    }
}

static void red_init_streams(RedWorker *worker)
{
    int i;

    ring_init(&worker->streams);
    worker->free_streams = NULL;
    for (i = 0; i < NUM_STREAMS; i++) {
        Stream *stream = &worker->streams_buf[i];
        ring_item_init(&stream->link);
        red_free_stream(worker, stream);
    }
}

#ifdef STREAM_TRACE

static inline int __red_is_next_stream_frame(RedWorker *worker,
                                             const Drawable *candidate,
                                             const int other_src_width,
                                             const int other_src_height,
                                             const SpiceRect *other_dest,
                                             const red_time_t other_time,
                                             const Stream *stream)
{
    QXLDrawable *qxl_drawable;

    if (candidate->creation_time - other_time >
            (stream ? RED_STREAM_CONTINUS_MAX_DELTA : RED_STREAM_DETACTION_MAX_DELTA)) {
        return FALSE;
    }

    qxl_drawable = candidate->qxl_drawable;

    if (!rect_is_equal(&qxl_drawable->bbox, other_dest)) {
        return FALSE;
    }

    SpiceRect* candidate_src = &qxl_drawable->u.copy.src_area;
    if (candidate_src->right - candidate_src->left != other_src_width ||
        candidate_src->bottom - candidate_src->top != other_src_height) {
        return FALSE;
    }

    if (stream) {
        QXLImage *qxl_image = (QXLImage *)get_virt(worker, qxl_drawable->u.copy.src_bitmap,
                                                   sizeof(QXLImage), candidate->group_id);
        if (stream->top_down != !!(qxl_image->bitmap.flags & SPICE_BITMAP_FLAGS_TOP_DOWN)) {
            return FALSE;
        }
    }
    return TRUE;
}

static inline int red_is_next_stream_frame(RedWorker *worker, const Drawable *candidate,
                                           const Drawable *prev)
{
    if (!candidate->streamable) {
        return FALSE;
    }

    SpiceRect* prev_src = &prev->qxl_drawable->u.copy.src_area;
    return __red_is_next_stream_frame(worker, candidate, prev_src->right - prev_src->left,
                                      prev_src->bottom - prev_src->top,
                                      &prev->qxl_drawable->bbox, prev->creation_time,
                                      prev->stream);
}

#else

static inline int red_is_next_stream_frame(RedWorker *worker, Drawable *candidate, Drawable *prev)
{
    QXLImage *qxl_image;
    QXLDrawable *qxl_drawable;
    QXLDrawable *prev_qxl_drawable;

    if (candidate->creation_time - prev->creation_time >
            ((prev->stream) ? RED_STREAM_CONTINUS_MAX_DELTA : RED_STREAM_DETACTION_MAX_DELTA)) {
        return FALSE;
    }

    qxl_drawable = candidate->qxl_drawable;
    prev_qxl_drawable = prev->qxl_drawable;
    if (qxl_drawable->type != QXL_DRAW_COPY || prev_qxl_drawable->type != QXL_DRAW_COPY) {
        return FALSE;
    }

    if (!rect_is_equal(&qxl_drawable->bbox, &prev_qxl_drawable->bbox)) {
        return FALSE;
    }

    if (!rect_is_same_size(&qxl_drawable->u.copy.src_area, &prev_qxl_drawable->u.copy.src_area)) {
        return FALSE;
    }

    if (qxl_drawable->u.copy.rop_decriptor != SPICE_ROPD_OP_PUT ||
                                    prev_qxl_drawable->u.copy.rop_decriptor != SPICE_ROPD_OP_PUT) {
        return FALSE;
    }

    qxl_image = (QXLImage *)get_virt(worker, qxl_drawable->u.copy.src_bitmap, sizeof(QXLImage),
                                     candidate->group_id);

    if (qxl_image->descriptor.type != SPICE_IMAGE_TYPE_BITMAP) {
        return FALSE;
    }

    if (prev->stream && prev->stream->top_down != !!(qxl_image->bitmap.flags & SPICE_BITMAP_FLAGS_TOP_DOWN)) {
        return FALSE;
    }

    return TRUE;
}

#endif

static void reset_rate(StreamAgent *stream_agent)
{
    Stream *stream = stream_agent->stream;
    AVCodecContext *new_ctx;
    int rate;

    rate = get_bit_rate(stream->width, stream->height);
    if (rate == stream->bit_rate) {
        return;
    }

    int stream_width = ALIGN(stream->width, 2);
    int stream_height = ALIGN(stream->height, 2);

    new_ctx = red_init_video_encoder(stream_width, stream_height);
    if (!new_ctx) {
        red_printf("craete ctx failed");
        return;
    }

    avcodec_close(stream->av_ctx);
    av_free(stream->av_ctx);
    stream->av_ctx = new_ctx;
    stream->bit_rate = rate;
}

static inline void pre_stream_item_swap(RedWorker *worker, Stream *stream)
{
    ASSERT(stream->current);

    if (!worker->display_channel || !IS_LOW_BANDWIDTH()) {
        return;
    }

    int index = stream - worker->streams_buf;
    StreamAgent *agent = &worker->display_channel->stream_agents[index];

    if (pipe_item_is_linked(&stream->current->pipe_item)) {
        ++agent->drops;
    }

    if (agent->frames / agent->fps < FPS_TEST_INTERVAL) {
        agent->frames++;
        return;
    }

    double drop_factor = ((double)agent->frames - (double)agent->drops) / (double)agent->frames;

    if (drop_factor == 1) {
        if (agent->fps < MAX_FPS) {
            agent->fps++;
        }
    } else if (drop_factor < 0.9) {
        if (agent->fps > 1) {
            agent->fps--;
        }
    }
    agent->frames = 1;
    agent->drops = 0;
}

static inline void red_update_copy_graduality(RedWorker* worker, Drawable *drawable)
{
    QXLImage *qxl_image;
    ASSERT(drawable->qxl_drawable->type == QXL_DRAW_COPY);

    if (worker->streaming_video != STREAM_VIDEO_FILTER) {
        drawable->copy_bitmap_graduality = BITMAP_GRADUAL_INVALID;
        return;
    }

    if (drawable->copy_bitmap_graduality != BITMAP_GRADUAL_INVALID) {
        return; // already set
    }

    qxl_image = (QXLImage *)get_virt(worker, drawable->qxl_drawable->u.copy.src_bitmap,
                                     sizeof(QXLImage), drawable->group_id);

    if (!BITMAP_FMT_IS_RGB[qxl_image->bitmap.format] || _stride_is_extra(&qxl_image->bitmap) ||
        (qxl_image->bitmap.flags & QXL_BITMAP_UNSTABLE)) {
        drawable->copy_bitmap_graduality = BITMAP_GRADUAL_NOT_AVAIL;
    } else  {
        if (_bitmap_is_gradual(worker, &qxl_image->bitmap, drawable->group_id)) {
            drawable->copy_bitmap_graduality = BITMAP_GRADUAL_TRUE;
        } else {
            drawable->copy_bitmap_graduality = BITMAP_GRADUAL_FALSE;
        }
    }
}

static inline int red_is_stream_start(Drawable *drawable)
{
    return ((drawable->frames_count >= RED_STREAM_FRAMES_START_CONDITION) &&
            (drawable->gradual_frames_count >=
            (RED_STREAM_GRADUAL_FRAMES_START_CONDITION * drawable->frames_count)));
}

static void red_stream_add_frame(RedWorker* worker, Drawable *frame_drawable,
                                 int frames_count,
                                 int gradual_frames_count,
                                 int last_gradual_frame)
{
    red_update_copy_graduality(worker, frame_drawable);
    frame_drawable->frames_count = frames_count + 1;
    frame_drawable->gradual_frames_count  = gradual_frames_count;

    if (frame_drawable->copy_bitmap_graduality != BITMAP_GRADUAL_FALSE) {
        if ((frame_drawable->frames_count - last_gradual_frame) >
            RED_STREAM_FRAMES_RESET_CONDITION) {
            frame_drawable->frames_count = 1;
            frame_drawable->gradual_frames_count = 1;
        } else {
            frame_drawable->gradual_frames_count++;
        }

        frame_drawable->last_gradual_frame = frame_drawable->frames_count;
    } else {
        frame_drawable->last_gradual_frame = last_gradual_frame;
    }

    if (red_is_stream_start(frame_drawable)) {
        red_create_stream(worker, frame_drawable);
    }
}

static inline void red_stream_maintenance(RedWorker *worker, Drawable *candidate, Drawable *prev)
{
    Stream *stream;

    if (candidate->stream) {
        return;
    }

#ifdef STREAM_TRACE
    if (!red_is_next_stream_frame(worker, candidate, prev)) {
        return;
    }
#else
    if ((worker->streaming_video == STREAM_VIDEO_OFF) ||
        !red_is_next_stream_frame(worker, candidate, prev) {
        return;
    }
#endif

    if ((stream = prev->stream)) {
#ifdef STREAM_TRACE
        pre_stream_item_swap(worker, stream);
        red_detach_stream(worker, stream);
        prev->streamable = FALSE; //prevent item trace
        red_attach_stream(worker, candidate, stream);
#else
        prev->stream = NULL;
        candidate->stream = stream;
        stream->current = candidate;

        if (!region_is_equal(&stream->region, &candidate->tree_item.base.rgn)) {
            region_destroy(&stream->region);
            region_clone(&stream->region, &candidate->tree_item.base.rgn);
            if (worker->display_channel) {
                int index = stream - worker->streams_buf;
                StreamAgent *stream_agent = &worker->display_channel->stream_agents[index];
                if (!pipe_item_is_linked(&stream_agent->clip_item)) {
                    stream->refs++;
                    red_pipe_add((RedChannel*)worker->display_channel, &stream_agent->clip_item);
                }
            }
        }
#endif
    } else {
        red_stream_add_frame(worker, candidate,
                             prev->frames_count,
                             prev->gradual_frames_count,
                             prev->last_gradual_frame);
    }
}

static inline int red_current_add_equal(RedWorker *worker, DrawItem *item, TreeItem *other)
{
    DrawItem *other_draw_item;
    Drawable *drawable;
    Drawable *other_drawable;

    if (other->type != TREE_ITEM_TYPE_DRAWABLE) {
        return FALSE;
    }
    other_draw_item = (DrawItem *)other;

    if (item->shadow || other_draw_item->shadow || item->effect != other_draw_item->effect) {
        return FALSE;
    }

    drawable = CONTAINEROF(item, Drawable, tree_item);
    other_drawable = CONTAINEROF(other_draw_item, Drawable, tree_item);

    if (item->effect == QXL_EFFECT_OPAQUE) {
        int add_after = !!other_drawable->stream;
        red_stream_maintenance(worker, drawable, other_drawable);
        __current_add_drawable(worker, drawable, &other->siblings_link);
        if (add_after) {
            red_pipe_add_drawable_after(worker, drawable, other_drawable);
        } else {
            red_pipe_add_drawable(worker, drawable);
        }
        remove_drawable(worker, other_drawable);
        return TRUE;
    }

    switch (item->effect) {
    case QXL_EFFECT_REVERT_ON_DUP:
        if (is_same_drawable(worker, drawable, other_drawable)) {
            if (!ring_item_is_linked(&other_drawable->pipe_item.link)) {
                red_pipe_add_drawable(worker, drawable);
            }
            remove_drawable(worker, other_drawable);
            return TRUE;
        }
        break;
    case QXL_EFFECT_OPAQUE_BRUSH:
        if (is_same_geometry(worker, drawable, other_drawable)) {
            __current_add_drawable(worker, drawable, &other->siblings_link);
            remove_drawable(worker, other_drawable);
            red_pipe_add_drawable(worker, drawable);
            return TRUE;
        }
        break;
    case QXL_EFFECT_NOP_ON_DUP:
        if (is_same_drawable(worker, drawable, other_drawable)) {
            return TRUE;
        }
        break;
    }
    return FALSE;
}

#ifdef STREAM_TRACE

static inline void red_use_stream_trace(RedWorker *worker, Drawable *drawable)
{
    ItemTrace *trace;
    ItemTrace *trace_end;
    Ring *ring;
    RingItem *item;

    if (drawable->stream || !drawable->streamable || drawable->frames_count) {
        return;
    }


    ring = &worker->streams;
    item = ring_get_head(ring);

    while (item) {
        Stream *stream = CONTAINEROF(item, Stream, link);
        if (!stream->current && __red_is_next_stream_frame(worker,
                                                           drawable,
                                                           stream->width,
                                                           stream->height,
                                                           &stream->dest_area,
                                                           stream->last_time,
                                                           stream)) {
            red_attach_stream(worker, drawable, stream);
            return;
        }
        item = ring_next(ring, item);
    }

    trace = worker->items_trace;
    trace_end = trace + NUM_TRACE_ITEMS;
    for (; trace < trace_end; trace++) {
        if (__red_is_next_stream_frame(worker, drawable, trace->width, trace->height,
                                       &trace->dest_area, trace->time, NULL)) {
            red_stream_add_frame(worker, drawable,
                                 trace->frames_count,
                                 trace->gradual_frames_count,
                                 trace->last_gradual_frame);
        }
    }
}

static void red_reset_stream_trace(RedWorker *worker)
{
    Ring *ring = &worker->streams;
    RingItem *item = ring_get_head(ring);

    while (item) {
        Stream *stream = CONTAINEROF(item, Stream, link);
        item = ring_next(ring, item);
        if (!stream->current) {
            red_stop_stream(worker, stream);
        } else {
            red_printf("attached stream");
        }
    }

    worker->next_item_trace = 0;
    memset(worker->items_trace, 0, sizeof(worker->items_trace));
}

#endif

static inline int red_current_add(RedWorker *worker, Drawable *drawable)
{
    DrawItem *item = &drawable->tree_item;
#ifdef RED_WORKER_STAT
    stat_time_t start_time = stat_now();
#endif
    RingItem *now;
    Ring *ring = &worker->current;
    QRegion exclude_rgn;
    RingItem *exclude_base = NULL;

    print_base_item("ADD", &item->base);
    ASSERT(!region_is_empty(&item->base.rgn));
    worker->current_size++;
    region_init(&exclude_rgn);
    now = ring_next(ring, ring);

    while (now) {
        TreeItem *sibling = CONTAINEROF(now, TreeItem, siblings_link);
        int test_res;

        if (!region_bounds_intersects(&item->base.rgn, &sibling->rgn)) {
            print_base_item("EMPTY", sibling);
            now = ring_next(ring, now);
            continue;
        }
        test_res = region_test(&item->base.rgn, &sibling->rgn, REGION_TEST_ALL);
        if (!(test_res & REGION_TEST_SHARED)) {
            print_base_item("EMPTY", sibling);
            now = ring_next(ring, now);
            continue;
        } else if (sibling->type != TREE_ITEM_TYPE_SHADOW) {
            if (!(test_res & REGION_TEST_RIGHT_EXCLUSIVE) &&
                                                   !(test_res & REGION_TEST_LEFT_EXCLUSIVE) &&
                                                   red_current_add_equal(worker, item, sibling)) {
                stat_add(&worker->add_stat, start_time);
                return FALSE;
            }

            if (!(test_res & REGION_TEST_RIGHT_EXCLUSIVE) && item->effect == QXL_EFFECT_OPAQUE) {
                Shadow *shadow;
                int skip = now == exclude_base;
                print_base_item("CONTAIN", sibling);

                if ((shadow = __find_shadow(sibling))) {
                    if (exclude_base) {
                        TreeItem *next = sibling;
                        exclude_region(worker, ring, exclude_base, &exclude_rgn, &next, NULL);
                        if (next != sibling) {
                            now = next ? &next->siblings_link : NULL;
                            exclude_base = NULL;
                            continue;
                        }
                    }
                    region_or(&exclude_rgn, &shadow->on_hold);
                }
                now = now->prev;
                current_remove(worker, sibling);
                now = ring_next(ring, now);
                if (shadow || skip) {
                    exclude_base = now;
                }
                continue;
            }

            if (!(test_res & REGION_TEST_LEFT_EXCLUSIVE) && is_opaque_item(sibling)) {
                Container *container;

                if (exclude_base) {
                    exclude_region(worker, ring, exclude_base, &exclude_rgn, NULL, NULL);
                    region_clear(&exclude_rgn);
                    exclude_base = NULL;
                }
                print_base_item("IN", sibling);
                if (sibling->type == TREE_ITEM_TYPE_CONTAINER) {
                    container = (Container *)sibling;
                    ring = &container->items;
                    item->base.container = container;
                    now = ring_next(ring, ring);
                    continue;
                }
                ASSERT(IS_DRAW_ITEM(sibling));
                if (!((DrawItem *)sibling)->container_root) {
                    container = __new_container(worker, (DrawItem *)sibling);
                    if (!container) {
                        red_printf("create new container failed");
                        region_destroy(&exclude_rgn);
                        return FALSE;
                    }
                    item->base.container = container;
                    ring = &container->items;
                }
            }
        }
        if (!exclude_base) {
            exclude_base = now;
        }
        break;
    }
    if (item->effect == QXL_EFFECT_OPAQUE) {
        region_or(&exclude_rgn, &item->base.rgn);
        exclude_region(worker, ring, exclude_base, &exclude_rgn, NULL, drawable);
#ifdef STREAM_TRACE
        red_use_stream_trace(worker, drawable);
#endif
        red_streams_update_clip(worker, drawable);
    } else {
#ifdef STREAM_TRACE
        red_detach_streams_behind(worker, &drawable->tree_item.base.rgn);
#else
        red_stop_streams_behind(worker, &drawable->tree_item.base.rgn);
#endif
    }
    region_destroy(&exclude_rgn);
    __current_add_drawable(worker, drawable, ring);
    stat_add(&worker->add_stat, start_time);
    return TRUE;
}

#else

static inline void __handle_remove_shadow(RedWorker *worker, TreeItem *item)
{
    Shadow *shadow;
    Ring *ring;

    while (item->type == TREE_ITEM_TYPE_CONTAINER) {
        if (!(item = (TreeItem *)ring_get_tail(&((Container *)item)->items))) {
            return;
        }
    }

    if (item->type != TREE_ITEM_TYPE_DRAWABLE || !(shadow = ((DrawItem *)item)->shadow)) {
        return;
    }
    print_base_item("SHADW", &shadow->base);
    ring = (shadow->base.container) ? &shadow->base.container->items : &worker->current;
    exclude_region(worker, ring, ring_next(ring, &shadow->base.siblings_link), &shadow->on_hold);
    region_clear(&shadow->on_hold);
}

static inline int red_current_add(RedWorker *worker, Drawable *drawable)
{
    DrawItem *item = &drawable->tree_item;
#ifdef RED_WORKER_STAT
    stat_time_t start_time = stat_now();
#endif
    RingItem *now;
    Ring *ring = &worker->current;

    print_base_item("ADD", &item->base);
    ASSERT(!region_is_empty(&item->base.rgn));
    worker->current_size++;
    now = ring_next(ring, ring);

    while (now) {
        TreeItem *sibling = CONTAINEROF(now, TreeItem, siblings_link);
        int test_res;

        if (!region_bounds_intersects(&item->base.rgn, &sibling->rgn)) {
            print_base_item("EMPTY", sibling);
            now = ring_next(ring, now);
            continue;
        }
        test_res = region_test(&item->base.rgn, &sibling->rgn, REGION_TEST_ALL);
        if (!(test_res & REGION_TEST_SHARED)) {
            print_base_item("EMPTY", sibling);
            now = ring_next(ring, now);
            continue;
        } else if (sibling->type != TREE_ITEM_TYPE_SHADOW) {
            if (!(test_res & REGION_TEST_RIGHT_EXCLUSIVE) && item->effect == QXL_EFFECT_OPAQUE) {
                print_base_item("CONTAIN", sibling);
                __handle_remove_shadow(worker, sibling);
                now = now->prev;
                current_remove(worker, sibling);
                now = ring_next(ring, now);
                continue;
            }

            if (!(test_res & REGION_TEST_LEFT_EXCLUSIVE) && is_opaque_item(sibling)) {
                Container *container;

                print_base_item("IN", sibling);
                if (sibling->type == TREE_ITEM_TYPE_CONTAINER) {
                    container = (Container *)sibling;
                    ring = &container->items;
                    item->base.container = container;
                    now = ring_next(ring, ring);
                    continue;
                }
                ASSERT(IS_DRAW_ITEM(sibling));
                if (!((DrawItem *)sibling)->container_root) {
                    container = __new_container(worker, (DrawItem *)sibling);
                    if (!container) {
                        red_printf("create new container failed");
                        return FALSE;
                    }
                    item->base.container = container;
                    ring = &container->items;
                }
            }
        }
        if (item->effect == QXL_EFFECT_OPAQUE) {
            QRegion exclude_rgn;
            region_clone(&exclude_rgn, &item->base.rgn);
            exclude_region(worker, ring, now, &exclude_rgn);
            region_destroy(&exclude_rgn);
        }
        break;
    }
    __current_add_drawable(worker, drawable, ring);
    stat_add(&worker->add_stat, start_time);
    return TRUE;
}

#endif

static void add_clip_rects(RedWorker *worker, QRegion *rgn, QXLPHYSICAL data, uint32_t group_id)
{
    while (data) {
        QXLDataChunk *chunk;
        SpiceRect *now;
        SpiceRect *end;
        uint32_t data_size;
        chunk = (QXLDataChunk *)get_virt(worker, data, sizeof(QXLDataChunk), group_id);
        data_size = chunk->data_size;
        validate_virt(worker, (unsigned long)chunk->data, get_memslot_id(worker, data), data_size,
                      group_id);
        now = (SpiceRect *)chunk->data;
        end = now + data_size / sizeof(SpiceRect);

        for (; now < end; now++) {
            SpiceRect* r = (SpiceRect *)now;

            ASSERT(now->top == r->top && now->left == r->left &&
                   now->bottom == r->bottom && now->right == r->right);
#ifdef PIPE_DEBUG
            printf("TEST: DRAWABLE: RECT: %u %u %u %u\n", r->top, r->left, r->bottom, r->right);
#endif
            region_add(rgn, r);
        }
        data = chunk->next_chunk;
    }
}

static inline Shadow *__new_shadow(RedWorker *worker, Drawable *item, SpicePoint *delta)
{
    if (!delta->x && !delta->y) {
        return NULL;
    }

    Shadow *shadow = malloc(sizeof(Shadow));
    if (!shadow) {
        return NULL;
    }
    worker->shadows_count++;
#ifdef PIPE_DEBUG
    shadow->base.id = ++worker->last_id;
#endif
    shadow->base.type = TREE_ITEM_TYPE_SHADOW;
    shadow->base.container = NULL;
    shadow->owner = &item->tree_item;
    region_clone(&shadow->base.rgn, &item->tree_item.base.rgn);
    region_offset(&shadow->base.rgn, delta->x, delta->y);
    ring_item_init(&shadow->base.siblings_link);
    region_init(&shadow->on_hold);
    item->tree_item.shadow = shadow;
    return shadow;
}

static inline int red_current_add_with_shadow(RedWorker *worker, Drawable *item, SpicePoint *delta)
{
#ifdef RED_WORKER_STAT
    stat_time_t start_time = stat_now();
#endif
    Ring *ring;

    Shadow *shadow = __new_shadow(worker, item, delta);
    if (!shadow) {
        stat_add(&worker->add_stat, start_time);
        return FALSE;
    }
    print_base_item("ADDSHADOW", &item->tree_item.base);
    worker->current_size++;
    ring = &worker->current;
    // item and his shadow must initially be placed in the same container.
    // for now putting them on root.
#ifdef STREAM_TRACE
    red_detach_streams_behind(worker, &shadow->base.rgn);
#else
    red_stop_streams_behind(worker, &shadow->base.rgn);
#endif
    ring_add(ring, &shadow->base.siblings_link);
    __current_add_drawable(worker, item, ring);
    if (item->tree_item.effect == QXL_EFFECT_OPAQUE) {
        QRegion exclude_rgn;
        region_clone(&exclude_rgn, &item->tree_item.base.rgn);
#ifdef USE_EXCLUDE_RGN
        exclude_region(worker, ring, &shadow->base.siblings_link, &exclude_rgn, NULL, NULL);
#else
        exclude_region(worker, ring, &shadow->base.siblings_link, &exclude_rgn);
#endif
        region_destroy(&exclude_rgn);
        red_streams_update_clip(worker, item);
    } else {
#ifdef STREAM_TRACE
        red_detach_streams_behind(worker, &item->tree_item.base.rgn);
#else
        red_stop_streams_behind(worker, &item->tree_item.base.rgn);
#endif
    }
    stat_add(&worker->add_stat, start_time);
    return TRUE;
}

static inline int has_shadow(QXLDrawable *drawable)
{
    return drawable->type == QXL_COPY_BITS;
}

#ifdef STREAM_TRACE
static inline void red_update_streamable(RedWorker *worker, Drawable *drawable,
                                         QXLDrawable *qxl_drawable)
{
    QXLImage *qxl_image;

    if (worker->streaming_video == STREAM_VIDEO_OFF) {
        return;
    }

    if (drawable->tree_item.effect != QXL_EFFECT_OPAQUE ||
                                        qxl_drawable->type != QXL_DRAW_COPY ||
                                        qxl_drawable->u.copy.rop_decriptor != SPICE_ROPD_OP_PUT) {
        return;
    }

    qxl_image = (QXLImage *)get_virt(worker, qxl_drawable->u.copy.src_bitmap, sizeof(QXLImage),
                                     drawable->group_id);
    if (qxl_image->descriptor.type != SPICE_IMAGE_TYPE_BITMAP) {
        return;
    }

    drawable->streamable = TRUE;
}

#endif

static inline int red_current_add_qxl(RedWorker *worker, Drawable *drawable,
                                      QXLDrawable *qxl_drawable)
{
    int ret;

    if (has_shadow(qxl_drawable)) {
        SpicePoint delta;

#ifdef RED_WORKER_STAT
        ++worker->add_with_shadow_count;
#endif
        delta.x = qxl_drawable->u.copy_bits.src_pos.x - qxl_drawable->bbox.left;
        delta.y = qxl_drawable->u.copy_bits.src_pos.y - qxl_drawable->bbox.top;
        ret = red_current_add_with_shadow(worker, drawable, &delta);
    } else {
#ifdef STREAM_TRACE
        red_update_streamable(worker, drawable, qxl_drawable);
#endif
        ret = red_current_add(worker, drawable);
    }
#ifdef RED_WORKER_STAT
    if ((++worker->add_count % 100) == 0) {
        stat_time_t total = worker->add_stat.total;
        red_printf("add with shadow count %u",
                   worker->add_with_shadow_count);
        worker->add_with_shadow_count = 0;
        red_printf("add[%u] %f exclude[%u] %f __exclude[%u] %f",
                   worker->add_stat.count,
                   stat_cpu_time_to_sec(total),
                   worker->exclude_stat.count,
                   stat_cpu_time_to_sec(worker->exclude_stat.total),
                   worker->__exclude_stat.count,
                   stat_cpu_time_to_sec(worker->__exclude_stat.total));
        red_printf("add %f%% exclude %f%% exclude2 %f%% __exclude %f%%",
                   (double)(total - worker->exclude_stat.total) / total * 100,
                   (double)(worker->exclude_stat.total) / total * 100,
                   (double)(worker->exclude_stat.total -
                            worker->__exclude_stat.total) / worker->exclude_stat.total * 100,
                   (double)(worker->__exclude_stat.total) / worker->exclude_stat.total * 100);
        stat_reset(&worker->add_stat);
        stat_reset(&worker->exclude_stat);
        stat_reset(&worker->__exclude_stat);
    }
#endif
    return ret;
}

static void red_get_area(RedWorker *worker, const SpiceRect *area, uint8_t *dest, int dest_stride,
                         int update)
{
    if (update) {
        red_update_area(worker, area);
    }

    worker->draw_funcs.read_pixels(worker->surface.context.canvas, dest, dest_stride, area);
}

static inline int red_handle_self_bitmap(RedWorker *worker, Drawable *drawable)
{
    QXLImage *image;
    int32_t width;
    int32_t height;
    uint8_t *dest;
    int dest_stride;

    if (!drawable->qxl_drawable->self_bitmap) {
        return TRUE;
    }

    width = drawable->qxl_drawable->bbox.right - drawable->qxl_drawable->bbox.left;
    height = drawable->qxl_drawable->bbox.bottom - drawable->qxl_drawable->bbox.top;
    dest_stride = width * sizeof(uint32_t);

    if (!(image = malloc(sizeof(QXLImage) + height * dest_stride))) {
        red_printf("alloc failed");
        return FALSE;
    }
    dest = (uint8_t *)(image + 1);

    image->descriptor.type = SPICE_IMAGE_TYPE_BITMAP;
    image->descriptor.flags = 0;

    QXL_SET_IMAGE_ID(image, QXL_IMAGE_GROUP_RED, ++worker->bits_unique);
    image->bitmap.flags = QXL_BITMAP_DIRECT | (worker->surface.context.top_down ?
                                               QXL_BITMAP_TOP_DOWN : 0);
    image->bitmap.format = SPICE_BITMAP_FMT_32BIT;
    image->bitmap.stride = dest_stride;
    image->descriptor.width = image->bitmap.x = width;
    image->descriptor.height = image->bitmap.y = height;
    image->bitmap.data = (QXLPHYSICAL)dest;
    image->bitmap.palette = 0;

    red_get_area(worker, &drawable->qxl_drawable->self_bitmap_area, dest, dest_stride, TRUE);

    drawable->self_bitmap = (uint8_t *)image;
    return TRUE;
}

static void free_one_drawable(RedWorker *worker, int force_glz_free)
{
    RingItem *ring_item = ring_get_tail(&worker->current_list);
    Drawable *drawable;
    Container *container;

    ASSERT(ring_item);
    drawable = CONTAINEROF(ring_item, Drawable, list_link);
    if (drawable->red_glz_drawable && force_glz_free) {
        ASSERT(worker->display_channel);
        red_display_free_glz_drawable(worker->display_channel, drawable->red_glz_drawable);
    }
    red_draw_drawable(worker, drawable);
    container = drawable->tree_item.base.container;
    current_remove_drawable(worker, drawable);
    container_cleanup(worker, container);
}

static Drawable *get_drawable(RedWorker *worker, uint8_t effect, QXLDrawable *qxl_drawable,
                              uint32_t group_id) {
    Drawable *drawable;
    struct timespec time;

    while (!(drawable = alloc_drawable(worker))) {
        free_one_drawable(worker, FALSE);
    }
    memset(drawable, 0, sizeof(Drawable));
    drawable->refs = 1;
    clock_gettime(CLOCK_MONOTONIC, &time);
    drawable->creation_time = timespec_to_red_time(&time);
#ifdef PIPE_DEBUG
    drawable->tree_item.base.id = ++worker->last_id;
#endif
    ring_item_init(&drawable->list_link);
#ifdef UPDATE_AREA_BY_TREE
    ring_item_init(&drawable->collect_link);
#endif
    ring_item_init(&drawable->tree_item.base.siblings_link);
    drawable->tree_item.base.type = TREE_ITEM_TYPE_DRAWABLE;
    region_init(&drawable->tree_item.base.rgn);
    drawable->tree_item.effect = effect;
    red_pipe_item_init(&drawable->pipe_item, PIPE_ITEM_TYPE_DRAW);
    drawable->qxl_drawable = qxl_drawable;
    drawable->group_id = group_id;

    return drawable;
}

static inline void red_process_drawable(RedWorker *worker, QXLDrawable *drawable, uint32_t group_id)
{
    Drawable *item = get_drawable(worker, drawable->effect, drawable, group_id);

    ASSERT(item);
    PANIC_ON(!worker->surface.context.canvas);
    ASSERT(worker->surface.refs != 0);

    worker->surface.refs++;

    region_add(&item->tree_item.base.rgn, &drawable->bbox);
#ifdef PIPE_DEBUG
    printf("TEST: DRAWABLE: id %u type %s effect %u bbox %u %u %u %u\n",
           item->tree_item.base.id,
           draw_type_to_str(drawable->type),
           item->tree_item.effect,
           drawable->bbox.top, drawable->bbox.left, drawable->bbox.bottom, drawable->bbox.right);
#endif

    if (drawable->clip.type == SPICE_CLIP_TYPE_RECTS) {
        QRegion rgn;

        region_init(&rgn);
        add_clip_rects(worker, &rgn, drawable->clip.data + OFFSETOF(QXLClipRects, chunk), group_id);
        region_and(&item->tree_item.base.rgn, &rgn);
        region_destroy(&rgn);
    } else if (drawable->clip.type == SPICE_CLIP_TYPE_PATH) {
        item->tree_item.effect = QXL_EFFECT_BLEND;
#ifdef PIPE_DEBUG
        printf("TEST: DRAWABLE: QXL_CLIP_TYPE_PATH\n");
#endif
    }

    if (region_is_empty(&item->tree_item.base.rgn)) {
        release_drawable(worker, item);
        return;
    }

    if (!red_handle_self_bitmap(worker, item)) {
        release_drawable(worker, item);
        return;
    }

    if (red_current_add_qxl(worker, item, drawable)) {
        worker->drawable_count++;
        if (item->tree_item.effect != QXL_EFFECT_OPAQUE) {
            worker->transparent_count++;
        }
        red_pipe_add_drawable(worker, item);
#ifdef DRAW_ALL
        red_draw_qxl_drawable(worker, item);
#endif
    }
    release_drawable(worker, item);
}

static void localize_path(RedWorker *worker, QXLPHYSICAL *in_path, uint32_t group_id)
{
    QXLPath *path;
    uint8_t *data;
    uint32_t data_size;
    QXLDataChunk *chunk;
    int memslot_id = get_memslot_id(worker, *in_path);

    ASSERT(in_path && *in_path);
    path = (QXLPath *)get_virt(worker, *in_path, sizeof(QXLPath), group_id);
    data = malloc(sizeof(UINT32) + path->data_size);
    ASSERT(data);
    *in_path = (QXLPHYSICAL)data;
    *(UINT32 *)data = path->data_size;
    data += sizeof(UINT32);
    chunk = &path->chunk;
    do {
        data_size = chunk->data_size;
        validate_virt(worker, (unsigned long)chunk->data, memslot_id, data_size, group_id);
        memcpy(data, chunk->data, data_size);
        data += data_size;
        chunk = chunk->next_chunk ? (QXLDataChunk *)get_virt(worker, chunk->next_chunk,
                                                             sizeof(QXLDataChunk), group_id) : NULL;
    } while (chunk);
}

static void unlocalize_path(QXLPHYSICAL *path)
{
    ASSERT(path && *path);
    free((void *)*path);
    *path = 0;
}

static void localize_str(RedWorker *worker, QXLPHYSICAL *in_str, uint32_t group_id)
{
    QXLString *qxl_str = (QXLString *)get_virt(worker, *in_str, sizeof(QXLString), group_id);
    QXLDataChunk *chunk;
    SpiceString *str;
    uint8_t *dest;
    uint32_t data_size;
    int memslot_id = get_memslot_id(worker, *in_str);

    ASSERT(in_str);
    str = malloc(sizeof(UINT32) + qxl_str->data_size);
    ASSERT(str);
    *in_str = (QXLPHYSICAL)str;
    str->length = qxl_str->length;
    str->flags = qxl_str->flags;
    dest = str->data;
    chunk = &qxl_str->chunk;
    for (;;) {
        QXLPHYSICAL next_chunk;

        data_size = chunk->data_size;
        validate_virt(worker, (unsigned long)chunk->data, memslot_id, data_size, group_id);
        memcpy(dest, chunk->data, data_size);
        if (!chunk->next_chunk) {
            return;
        }
        dest += data_size;
        next_chunk = chunk->next_chunk;
        memslot_id = get_memslot_id(worker, next_chunk);
        chunk = (QXLDataChunk *)get_virt(worker, next_chunk, sizeof(QXLDataChunk), group_id);
    }
}

static void unlocalize_str(QXLPHYSICAL *str)
{
    ASSERT(str && *str);
    free((void *)*str);
    *str = 0;
}

static void localize_clip(RedWorker *worker, SpiceClip *clip, uint32_t group_id)
{
    switch (clip->type) {
    case SPICE_CLIP_TYPE_NONE:
        return;
    case SPICE_CLIP_TYPE_RECTS: {
        QXLClipRects *clip_rects;
        QXLDataChunk *chunk;
        int memslot_id = get_memslot_id(worker, clip->data);
        uint8_t *data;
        uint32_t data_size;
        clip_rects = (QXLClipRects *)get_virt(worker, clip->data, sizeof(QXLClipRects), group_id);
        chunk = &clip_rects->chunk;
        ASSERT(clip->data);
        data = malloc(sizeof(UINT32) + clip_rects->num_rects * sizeof(SpiceRect));
        ASSERT(data);
        clip->data = (QXLPHYSICAL)data;
        *(UINT32 *)(data) = clip_rects->num_rects;
        data += sizeof(UINT32);
        do {
            data_size = chunk->data_size;
            validate_virt(worker, (unsigned long)chunk->data, memslot_id, data_size, group_id);
            memcpy(data, chunk->data, data_size);
            data += data_size;
            chunk = chunk->next_chunk ? (QXLDataChunk *)get_virt(worker, chunk->next_chunk,
                                                                 sizeof(QXLDataChunk), group_id) :
                                         NULL;
        } while (chunk);
        break;
    }
    case SPICE_CLIP_TYPE_PATH:
        localize_path(worker, &clip->data, group_id);
        break;
    default:
        red_printf("invalid clip type");
    }
}

static void unlocalize_clip(SpiceClip *clip)
{
    switch (clip->type) {
    case SPICE_CLIP_TYPE_NONE:
        return;
    case SPICE_CLIP_TYPE_RECTS:
        free((void *)clip->data);
        clip->data = 0;
        break;
    case SPICE_CLIP_TYPE_PATH:
        unlocalize_path(&clip->data);
        break;
    default:
        red_printf("invalid clip type");
    }
}

static LocalImage *alloc_local_image(RedWorker *worker)
{
    ASSERT(worker->local_images_pos < MAX_BITMAPS);
    return &worker->local_images[worker->local_images_pos++];
}

static ImageCacheItem *image_cache_find(ImageCache *cache, UINT64 id)
{
    ImageCacheItem *item = cache->hash_table[id % IMAGE_CACHE_HASH_SIZE];

    while (item) {
        if (item->id == id) {
            return item;
        }
        item = item->next;
    }
    return NULL;
}

static int image_cache_hit(ImageCache *cache, UINT64 id)
{
    ImageCacheItem *item;
    if (!(item = image_cache_find(cache, id))) {
        return FALSE;
    }
#ifdef IMAGE_CACHE_AGE
    item->age = cache->age;
#endif
    ring_remove(&item->lru_link);
    ring_add(&cache->lru, &item->lru_link);
    return TRUE;
}

static void image_cache_remove(ImageCache *cache, ImageCacheItem *item)
{
    ImageCacheItem **now;

    now = &cache->hash_table[item->id % IMAGE_CACHE_HASH_SIZE];
    for (;;) {
        ASSERT(*now);
        if (*now == item) {
            *now = item->next;
            break;
        }
        now = &(*now)->next;
    }
    ring_remove(&item->lru_link);
    cairo_surface_destroy(item->surf);
    free(item);
#ifndef IMAGE_CACHE_AGE
    cache->num_items--;
#endif
}

#define IMAGE_CACHE_MAX_ITEMS 2

static void image_cache_put(void *opaque, uint64_t id, cairo_surface_t *surface)
{
    ImageCache *cache = (ImageCache *)opaque;
    ImageCacheItem *item;

#ifndef IMAGE_CACHE_AGE
    if (cache->num_items == IMAGE_CACHE_MAX_ITEMS) {
        ImageCacheItem *tail = (ImageCacheItem *)ring_get_tail(&cache->lru);
        ASSERT(tail);
        image_cache_remove(cache, tail);
    }
#endif

    if (!(item = (ImageCacheItem *)malloc(sizeof(ImageCacheItem)))) {
        red_error("alloc failed");
    }
    item->id = id;
#ifdef IMAGE_CACHE_AGE
    item->age = cache->age;
#else
    cache->num_items++;
#endif
    item->surf = cairo_surface_reference(surface);
    ring_item_init(&item->lru_link);

    item->next = cache->hash_table[item->id % IMAGE_CACHE_HASH_SIZE];
    cache->hash_table[item->id % IMAGE_CACHE_HASH_SIZE] = item;

    ring_add(&cache->lru, &item->lru_link);
}

static cairo_surface_t *image_cache_get(void *opaque, uint64_t id)
{
    ImageCache *cache = (ImageCache *)opaque;

    ImageCacheItem *item = image_cache_find(cache, id);
    if (!item) {
        red_error("not found");
    }
    return cairo_surface_reference(item->surf);
}

static void image_cache_init(ImageCache *cache)
{
    memset(cache->hash_table, 0, sizeof(cache->hash_table));
    ring_init(&cache->lru);
#ifdef IMAGE_CACHE_AGE
    cache->age = 0;
#else
    cache->num_items = 0;
#endif
}

static void image_cache_reset(ImageCache *cache)
{
    ImageCacheItem *item;

    while ((item = (ImageCacheItem *)ring_get_head(&cache->lru))) {
        image_cache_remove(cache, item);
    }
#ifdef IMAGE_CACHE_AGE
    cache->age = 0;
#endif
}

#define IMAGE_CACHE_DEPTH 4

static void image_cache_eaging(ImageCache *cache)
{
#ifdef IMAGE_CACHE_AGE
    ImageCacheItem *item;

    cache->age++;
    while ((item = (ImageCacheItem *)ring_get_tail(&cache->lru)) &&
           cache->age - item->age > IMAGE_CACHE_DEPTH) {
        image_cache_remove(cache, item);
    }
#endif
}

static void localize_bitmap(RedWorker *worker, QXLPHYSICAL *in_bitmap, uint32_t group_id)
{
    QXLImage *image;
    QXLImage *local_image;

    ASSERT(in_bitmap && *in_bitmap);
    image = (QXLImage *)get_virt(worker, *in_bitmap, sizeof(QXLImage), group_id);
    local_image = (QXLImage *)alloc_local_image(worker);
    *local_image = *image;
    *in_bitmap = (QXLPHYSICAL)local_image;
    local_image->descriptor.flags = 0;

    if (image_cache_hit(&worker->image_cache, local_image->descriptor.id)) {
        local_image->descriptor.type = SPICE_IMAGE_TYPE_FROM_CACHE;
        return;
    }

    switch (local_image->descriptor.type) {
    case SPICE_IMAGE_TYPE_QUIC: {
        QXLDataChunk **chanks_head;
#ifdef IMAGE_CACHE_AGE
        local_image->descriptor.flags |= SPICE_IMAGE_FLAGS_CACHE_ME;
#else
        if (local_image->descriptor.width * local_image->descriptor.height >= 640 * 480) {
            local_image->descriptor.flags |= SPICE_IMAGE_FLAGS_CACHE_ME;
        }
#endif
        chanks_head = (QXLDataChunk **)local_image->quic.data;
        *chanks_head = (QXLDataChunk *)image->quic.data;
        break;
    }
    case SPICE_IMAGE_TYPE_BITMAP:
        if (image->bitmap.flags & QXL_BITMAP_DIRECT) {
            local_image->bitmap.data = (QXLPHYSICAL)get_virt(worker, image->bitmap.data,
                                                          image->bitmap.stride * image->bitmap.y,
                                                          group_id);
        } else {
            QXLPHYSICAL src_data;
            int size = image->bitmap.y * image->bitmap.stride;
            uint8_t *data = malloc(size);
            ASSERT(data);
            local_image->bitmap.data = (QXLPHYSICAL)data;
            src_data = image->bitmap.data;

            while (size) {
                QXLDataChunk *chunk;
                uint32_t data_size;
                int cp_size;

                ASSERT(src_data);
                chunk = (QXLDataChunk *)get_virt(worker, src_data, sizeof(QXLDataChunk), group_id);
                data_size = chunk->data_size;
                validate_virt(worker, (unsigned long)chunk->data, get_memslot_id(worker, src_data),
                              data_size, group_id);
                cp_size = MIN(data_size, size);
                memcpy(data, chunk->data, cp_size);
                data += cp_size;
                size -= cp_size;
                src_data = chunk->next_chunk;
            }
        }

        if (local_image->bitmap.palette) {
            uint16_t num_ents;
            uint32_t *ents;
            SpicePalette *tmp_palette;
            SpicePalette *shadow_palette;

            int slot_id = get_memslot_id(worker, local_image->bitmap.palette);
            tmp_palette = (SpicePalette *)get_virt(worker, local_image->bitmap.palette,
                                              sizeof(SpicePalette), group_id);

            num_ents = tmp_palette->num_ents;
            ents = tmp_palette->ents;

            validate_virt(worker, (unsigned long)ents, slot_id, (num_ents * sizeof(uint32_t)),
                          group_id);

            shadow_palette = (SpicePalette *)malloc(sizeof(SpicePalette) + num_ents * sizeof(uint32_t) +
                                               sizeof(QXLPHYSICAL));
            if (!shadow_palette) {
                PANIC("SpicePalette malloc failed");
            }

            memcpy(shadow_palette->ents, ents, num_ents * sizeof(uint32_t));
            shadow_palette->num_ents = num_ents;
            shadow_palette->unique = tmp_palette->unique;

            local_image->bitmap.palette = (SPICE_ADDRESS)shadow_palette;
        }
        break;
    default:
        red_error("invalid image type");
    }
}

static void unlocalize_bitmap(QXLPHYSICAL *bitmap)
{
    QXLImage *image;

    ASSERT(bitmap && *bitmap);
    image = (QXLImage *)*bitmap;
    *bitmap = 0;

    switch (image->descriptor.type) {
    case SPICE_IMAGE_TYPE_BITMAP:
        if (!(image->bitmap.flags & QXL_BITMAP_DIRECT)) {
            free((void *)image->bitmap.data);
        }
        if (image->bitmap.palette) {
            free((void *)image->bitmap.palette);
        }
        break;
    case SPICE_IMAGE_TYPE_QUIC:
    case SPICE_IMAGE_TYPE_FROM_CACHE:
        *bitmap = 0;
        break;
    default:
        red_error("invalid image type %u", image->descriptor.type);
    }
}

static void localize_brush(RedWorker *worker, SpiceBrush *brush, uint32_t group_id)
{
    if (brush->type == SPICE_BRUSH_TYPE_PATTERN) {
        localize_bitmap(worker, &brush->u.pattern.pat, group_id);
    }
}

static void unlocalize_brush(SpiceBrush *brush)
{
    if (brush->type == SPICE_BRUSH_TYPE_PATTERN) {
        unlocalize_bitmap(&brush->u.pattern.pat);
    }
}

static void localize_mask(RedWorker *worker, SpiceQMask *mask, uint32_t group_id)
{
    if (mask->bitmap) {
        localize_bitmap(worker, &mask->bitmap, group_id);
    }
}

static void unlocalize_mask(SpiceQMask *mask)
{
    if (mask->bitmap) {
        unlocalize_bitmap(&mask->bitmap);
    }
}

static void localize_attr(RedWorker *worker, SpiceLineAttr *attr, uint32_t group_id)
{
    if (attr->style_nseg) {
        uint8_t *buf;
        uint8_t *data;

        ASSERT(attr->style);
        buf = (uint8_t *)get_virt(worker, attr->style, attr->style_nseg * sizeof(uint32_t),
                                  group_id);
        data = malloc(attr->style_nseg * sizeof(uint32_t));
        ASSERT(data);
        memcpy(data, buf, attr->style_nseg * sizeof(uint32_t));
        attr->style = (QXLPHYSICAL)data;
    }
}

static void unlocalize_attr(SpiceLineAttr *attr)
{
    if (attr->style_nseg) {
        free((void *)attr->style);
        attr->style = 0;
    }
}

static void red_draw_qxl_drawable(RedWorker *worker, Drawable *drawable)
{
    SpiceClip clip = drawable->qxl_drawable->clip;

    worker->local_images_pos = 0;
    image_cache_eaging(&worker->image_cache);

    worker->preload_group_id = drawable->group_id;

    localize_clip(worker, &clip, drawable->group_id);
    switch (drawable->qxl_drawable->type) {
    case QXL_DRAW_FILL: {
        SpiceFill fill = drawable->qxl_drawable->u.fill;
        localize_brush(worker, &fill.brush, drawable->group_id);
        localize_mask(worker, &fill.mask, drawable->group_id);
        worker->draw_funcs.draw_fill(worker->surface.context.canvas, &drawable->qxl_drawable->bbox,
                                     &clip, &fill); unlocalize_mask(&fill.mask);
        unlocalize_brush(&fill.brush);
        break;
    }
    case QXL_DRAW_OPAQUE: {
        SpiceOpaque opaque = drawable->qxl_drawable->u.opaque;
        localize_brush(worker, &opaque.brush, drawable->group_id);
        localize_bitmap(worker, &opaque.src_bitmap, drawable->group_id);
        localize_mask(worker, &opaque.mask, drawable->group_id);
        worker->draw_funcs.draw_opaque(worker->surface.context.canvas,
                                       &drawable->qxl_drawable->bbox, &clip, &opaque);
        unlocalize_mask(&opaque.mask);
        unlocalize_bitmap(&opaque.src_bitmap);
        unlocalize_brush(&opaque.brush);
        break;
    }
    case QXL_DRAW_COPY: {
        SpiceCopy copy = drawable->qxl_drawable->u.copy;
        localize_bitmap(worker, &copy.src_bitmap, drawable->group_id);
        localize_mask(worker, &copy.mask, drawable->group_id);
        worker->draw_funcs.draw_copy(worker->surface.context.canvas, &drawable->qxl_drawable->bbox,
                                     &clip, &copy);
        unlocalize_mask(&copy.mask);
        unlocalize_bitmap(&copy.src_bitmap);
        break;
    }
    case QXL_DRAW_TRANSPARENT: {
        SpiceTransparent transparent = drawable->qxl_drawable->u.transparent;
        localize_bitmap(worker, &transparent.src_bitmap, drawable->group_id);
        worker->draw_funcs.draw_transparent(worker->surface.context.canvas,
                                            &drawable->qxl_drawable->bbox, &clip, &transparent);
        unlocalize_bitmap(&transparent.src_bitmap);
        break;
    }
    case QXL_DRAW_ALPHA_BLEND: {
        SpiceAlphaBlnd alpha_blend = drawable->qxl_drawable->u.alpha_blend;
        localize_bitmap(worker, &alpha_blend.src_bitmap, drawable->group_id);
        worker->draw_funcs.draw_alpha_blend(worker->surface.context.canvas,
                                            &drawable->qxl_drawable->bbox, &clip, &alpha_blend);
        unlocalize_bitmap(&alpha_blend.src_bitmap);
        break;
    }
    case QXL_COPY_BITS: {
        worker->draw_funcs.copy_bits(worker->surface.context.canvas, &drawable->qxl_drawable->bbox,
                                     &clip, &drawable->qxl_drawable->u.copy_bits.src_pos);
        break;
    }
    case QXL_DRAW_BLEND: {
        SpiceBlend blend = drawable->qxl_drawable->u.blend;
        localize_bitmap(worker, &blend.src_bitmap, drawable->group_id);
        localize_mask(worker, &blend.mask, drawable->group_id);
        worker->draw_funcs.draw_blend(worker->surface.context.canvas, &drawable->qxl_drawable->bbox,
                                      &clip, &blend);
        unlocalize_mask(&blend.mask);
        unlocalize_bitmap(&blend.src_bitmap);
        break;
    }
    case QXL_DRAW_BLACKNESS: {
        SpiceBlackness blackness = drawable->qxl_drawable->u.blackness;
        localize_mask(worker, &blackness.mask, drawable->group_id);
        worker->draw_funcs.draw_blackness(worker->surface.context.canvas,
                                          &drawable->qxl_drawable->bbox, &clip, &blackness);
        unlocalize_mask(&blackness.mask);
        break;
    }
    case QXL_DRAW_WHITENESS: {
        SpiceWhiteness whiteness = drawable->qxl_drawable->u.whiteness;
        localize_mask(worker, &whiteness.mask, drawable->group_id);
        worker->draw_funcs.draw_whiteness(worker->surface.context.canvas,
                                          &drawable->qxl_drawable->bbox, &clip, &whiteness);
        unlocalize_mask(&whiteness.mask);
        break;
    }
    case QXL_DRAW_INVERS: {
        SpiceInvers invers = drawable->qxl_drawable->u.invers;
        localize_mask(worker, &invers.mask, drawable->group_id);
        worker->draw_funcs.draw_invers(worker->surface.context.canvas,
                                       &drawable->qxl_drawable->bbox, &clip, &invers);
        unlocalize_mask(&invers.mask);
        break;
    }
    case QXL_DRAW_ROP3: {
        SpiceRop3 rop3 = drawable->qxl_drawable->u.rop3;
        localize_brush(worker, &rop3.brush, drawable->group_id);
        localize_bitmap(worker, &rop3.src_bitmap, drawable->group_id);
        localize_mask(worker, &rop3.mask, drawable->group_id);
        worker->draw_funcs.draw_rop3(worker->surface.context.canvas, &drawable->qxl_drawable->bbox,
                                     &clip, &rop3); unlocalize_mask(&rop3.mask);
        unlocalize_bitmap(&rop3.src_bitmap);
        unlocalize_brush(&rop3.brush);
        break;
    }
    case QXL_DRAW_STROKE: {
        SpiceStroke stroke = drawable->qxl_drawable->u.stroke;
        localize_brush(worker, &stroke.brush, drawable->group_id);
        localize_path(worker, &stroke.path, drawable->group_id);
        localize_attr(worker, &stroke.attr, drawable->group_id);
        worker->draw_funcs.draw_stroke(worker->surface.context.canvas,
                                       &drawable->qxl_drawable->bbox, &clip, &stroke);
        unlocalize_attr(&stroke.attr);
        unlocalize_path(&stroke.path);
        unlocalize_brush(&stroke.brush);
        break;
    }
    case QXL_DRAW_TEXT: {
        SpiceText text = drawable->qxl_drawable->u.text;
        localize_brush(worker, &text.fore_brush, drawable->group_id);
        localize_brush(worker, &text.back_brush, drawable->group_id);
        localize_str(worker, &text.str, drawable->group_id);
        worker->draw_funcs.draw_text(worker->surface.context.canvas, &drawable->qxl_drawable->bbox,
                                     &clip, &text);
        unlocalize_str(&text.str);
        unlocalize_brush(&text.back_brush);
        unlocalize_brush(&text.fore_brush);
        break;
    }
    default:
        red_printf("invlaid type");
    }
    unlocalize_clip(&clip);
}

#ifndef DRAW_ALL

static void red_draw_drawable(RedWorker *worker, Drawable *drawable)
{
#ifdef UPDATE_AREA_BY_TREE
    //todo: add need top mask flag
    worker->draw_funcs.set_top_mask(worker->surface.context.canvas,
                                    drawable->tree_item.base.rgn.num_rects,
                                    drawable->tree_item.base.rgn.rects);
#endif
    red_draw_qxl_drawable(worker, drawable);
#ifdef UPDATE_AREA_BY_TREE
    worker->draw_funcs.clear_top_mask(worker->surface.context.canvas);
#endif
}

#ifdef UPDATE_AREA_BY_TREE

static inline void __red_collect_for_update(RedWorker *worker, Ring *ring, RingItem *ring_item,
                                            QRegion *rgn, Ring *items)
{
    Ring *top_ring = ring;

    for (;;) {
        TreeItem *now = CONTAINEROF(ring_item, TreeItem, siblings_link);
        Container *container = now->container;
        if (region_intersects(rgn, &now->rgn)) {
            if (IS_DRAW_ITEM(now)) {
                Drawable *drawable = CONTAINEROF(now, Drawable, tree_item);

                ring_add(items, &drawable->collect_link);
                region_or(rgn, &now->rgn);
                if (drawable->tree_item.shadow) {
                    region_or(rgn, &drawable->tree_item.shadow->base.rgn);
                }
            } else if (now->type == TREE_ITEM_TYPE_SHADOW) {
                Drawable *owner = CONTAINEROF(((Shadow *)now)->owner, Drawable, tree_item);
                if (!ring_item_is_linked(&owner->collect_link)) {
                    region_or(rgn, &now->rgn);
                    region_or(rgn, &owner->tree_item.base.rgn);
                    ring_add(items, &owner->collect_link);
                }
            } else if (now->type == TREE_ITEM_TYPE_CONTAINER) {
                Container *container = (Container *)now;

                if ((ring_item = ring_get_head(&container->items))) {
                    ring = &container->items;
                    ASSERT(((TreeItem *)ring_item)->container);
                    continue;
                }
                ring_item = &now->siblings_link;
            }
        }

        while (!(ring_item = ring_next(ring, ring_item))) {
            if (ring == top_ring) {
                return;
            }
            ring_item = &container->base.siblings_link;
            container = container->base.container;
            ring = (container) ? &container->items : top_ring;
        }
    }
}

static void red_update_area(RedWorker *worker, const SpiceRect *area)
{
    Ring *ring = &worker->current;
    RingItem *ring_item;
    Ring items;
    QRegion rgn;

    if (!(ring_item = ring_get_head(ring))) {
        worker->draw_context.validate_area(worker->draw_context.canvas,
                                           &worker->dev_info.surface0_area, area);
        return;
    }

    region_init(&rgn);
    region_add(&rgn, area);
    ring_init(&items);
    __red_collect_for_update(worker, ring, ring_item, &rgn, &items);
    region_destroy(&rgn);

    while ((ring_item = ring_get_head(&items))) {
        Drawable *drawable = CONTAINEROF(ring_item, Drawable, collect_link);
        Container *container;

        ring_remove(ring_item);
        red_draw_drawable(worker, drawable);
        container = drawable->tree_item.base.container;
        current_remove_drawable(worker, drawable);
        container_cleanup(worker, container);
    }
    worker->draw_funcs.validate_area(worker->surface.context.canvas, worker->surface.context.stride,
                                     worker->surface.context.line_0, area);
}

#else

static void red_update_area(RedWorker *worker, const SpiceRect *area)
{
    Ring *ring = &worker->current_list;
    RingItem *ring_item = ring;
    QRegion rgn;
    Drawable *last = NULL;
    Drawable *now;

    region_init(&rgn);
    region_add(&rgn, area);
    while ((ring_item = ring_next(ring, ring_item))) {
        now = CONTAINEROF(ring_item, Drawable, list_link);
        if (region_intersects(&rgn, &now->tree_item.base.rgn)) {
            last = now;
            break;
        }
    }
    region_destroy(&rgn);

    if (!last) {
        worker->draw_funcs.validate_area(worker->surface.context.canvas,
                                         worker->surface.context.stride,
                                         worker->surface.context.line_0, area);
        return;
    }

    do {
        Container *container;

        ring_item = ring_get_tail(&worker->current_list);
        now = CONTAINEROF(ring_item, Drawable, list_link);
        red_draw_drawable(worker, now);
        container = now->tree_item.base.container;
        current_remove_drawable(worker, now);
        container_cleanup(worker, container);
    } while (now != last);
    worker->draw_funcs.validate_area(worker->surface.context.canvas, worker->surface.context.stride,
                                     worker->surface.context.line_0, area);
}

#endif

#endif

static inline void free_cursor_item(RedWorker *worker, CursorItem *item);

static void red_release_cursor(RedWorker *worker, CursorItem *cursor)
{
    if (!--cursor->refs) {
        QXLReleaseInfoExt release_info_ext;
        QXLCursorCmd *cursor_cmd;

        if (cursor->type == CURSOR_TYPE_LOCAL) {
            free(cursor);
            return;
        }

        cursor_cmd = cursor->qxl_cursor;
        release_info_ext.group_id = cursor->group_id;
        release_info_ext.info = &cursor_cmd->release_info;
        worker->qxl->release_resource(worker->qxl, release_info_ext);
        free_cursor_item(worker, cursor);
    }
}

static void red_set_cursor(RedWorker *worker, CursorItem *cursor)
{
    if (worker->cursor) {
        red_release_cursor(worker, worker->cursor);
    }
    ++cursor->refs;
    worker->cursor = cursor;
}

static inline CursorItem *alloc_cursor_item(RedWorker *worker)
{
    CursorItem *cursor;
    if (!worker->free_cursor_items) {
        return NULL;
    }
    cursor = &worker->free_cursor_items->u.cursor_item;
    worker->free_cursor_items = worker->free_cursor_items->u.next;
    return cursor;
}

static inline void free_cursor_item(RedWorker *worker, CursorItem *item)
{
    ((_CursorItem *)item)->u.next = worker->free_cursor_items;
    worker->free_cursor_items = (_CursorItem *)item;
}

static void cursor_items_init(RedWorker *worker)
{
    int i;

    worker->free_cursor_items = NULL;
    for (i = 0; i < NUM_CURSORS; i++) {
        free_cursor_item(worker, &worker->cursor_items[i].u.cursor_item);
    }
}

static CursorItem *get_cursor_item(RedWorker *worker, QXLCursorCmd *cmd, uint32_t group_id)
{
    CursorItem *cursor_item;

    PANIC_ON(!(cursor_item = alloc_cursor_item(worker)));

    cursor_item->refs = 1;
    red_pipe_item_init(&cursor_item->pipe_data, PIPE_ITEM_TYPE_CURSOR);
    cursor_item->type = CURSOR_TYPE_INVALID;
    cursor_item->group_id = group_id;
    cursor_item->qxl_cursor = cmd;

    return cursor_item;
}

void qxl_process_cursor(RedWorker *worker, QXLCursorCmd *cursor_cmd, uint32_t group_id)
{
    CursorItem *item = get_cursor_item(worker, cursor_cmd, group_id);
    int cursor_show = FALSE;

    switch (cursor_cmd->type) {
    case QXL_CURSOR_SET:
        worker->cursor_visible = cursor_cmd->u.set.visible;
        item->type = CURSOR_TYPE_DEV;
        red_set_cursor(worker, item);
        break;
    case QXL_CURSOR_MOVE:
        cursor_show = !worker->cursor_visible;
        worker->cursor_visible = TRUE;
        worker->cursor_position = cursor_cmd->u.position;
        break;
    case QXL_CURSOR_HIDE:
        worker->cursor_visible = FALSE;
        break;
    case QXL_CURSOR_TRAIL:
        worker->cursor_trail_length = cursor_cmd->u.trail.length;
        worker->cursor_trail_frequency = cursor_cmd->u.trail.frequency;
        break;
    default:
        red_error("invalid cursor command %u", cursor_cmd->type);
    }

    if (worker->cursor_channel && (worker->mouse_mode == SPICE_MOUSE_MODE_SERVER ||
                                   cursor_cmd->type != QXL_CURSOR_MOVE || cursor_show)) {
        red_pipe_add(&worker->cursor_channel->base, &item->pipe_data);
    } else {
        red_release_cursor(worker, item);
    }
}

static inline uint64_t red_now()
{
    struct timespec time;

    clock_gettime(CLOCK_MONOTONIC, &time);

    return time.tv_sec * 1000000000 + time.tv_nsec;
}

static int red_process_cursor(RedWorker *worker, uint32_t max_pipe_size)
{
    QXLCommandExt ext_cmd;
    int n = 0;

    while (!worker->cursor_channel || worker->cursor_channel->base.pipe_size <= max_pipe_size) {
        if (!worker->qxl->get_cursor_command(worker->qxl, &ext_cmd)) {
            if (worker->repoll_cursor_ring < CMD_RING_POLL_RETRIES) {
                worker->repoll_cursor_ring++;
                worker->epoll_timeout = MIN(worker->epoll_timeout, CMD_RING_POLL_TIMEOUT);
                break;
            }
            if (worker->repoll_cursor_ring > CMD_RING_POLL_RETRIES ||
                worker->qxl->req_cursor_notification(worker->qxl)) {
                worker->repoll_cursor_ring++;
                break;
            }
            continue;
        }
        worker->repoll_cursor_ring = 0;
        switch (ext_cmd.cmd.type) {
        case QXL_CMD_CURSOR: {
            QXLCursorCmd *cursor_cmd = (QXLCursorCmd *)get_virt(worker, ext_cmd.cmd.data,
                                                                sizeof(QXLCursorCmd),
                                                                ext_cmd.group_id);
            qxl_process_cursor(worker, cursor_cmd, ext_cmd.group_id);
            break;
        }
        default:
            red_error("bad command type");
        }
        n++;
    }
    return n;
}

static int red_process_commands(RedWorker *worker, uint32_t max_pipe_size)
{
    QXLCommandExt ext_cmd;
    int n = 0;
    uint64_t start = red_now();

    while (!worker->display_channel || worker->display_channel->base.pipe_size <= max_pipe_size) {
        if (!worker->qxl->get_command(worker->qxl, &ext_cmd)) {
            if (worker->repoll_cmd_ring < CMD_RING_POLL_RETRIES) {
                worker->repoll_cmd_ring++;
                worker->epoll_timeout = MIN(worker->epoll_timeout, CMD_RING_POLL_TIMEOUT);
                break;
            }
            if (worker->repoll_cmd_ring > CMD_RING_POLL_RETRIES ||
                         worker->qxl->req_cmd_notification(worker->qxl)) {
                worker->repoll_cmd_ring++;
                break;
            }
            continue;
        }
        stat_inc_counter(worker->command_counter, 1);
        worker->repoll_cmd_ring = 0;
        switch (ext_cmd.cmd.type) {
        case QXL_CMD_DRAW: {
            QXLDrawable *drawable = (QXLDrawable *)get_virt(worker, ext_cmd.cmd.data,
                                                            sizeof(QXLDrawable), ext_cmd.group_id);
            red_process_drawable(worker, drawable, ext_cmd.group_id);
            break;
        }
        case QXL_CMD_UPDATE: {
            QXLReleaseInfoExt release_info_ext;
            QXLUpdateCmd *draw_cmd = (QXLUpdateCmd *)get_virt(worker, ext_cmd.cmd.data,
                                                              sizeof(QXLUpdateCmd),
                                                              ext_cmd.group_id);
            red_update_area(worker, &draw_cmd->area);
            worker->qxl->notify_update(worker->qxl, draw_cmd->update_id);
            release_info_ext.group_id = ext_cmd.group_id;
            release_info_ext.info = &draw_cmd->release_info;
            worker->qxl->release_resource(worker->qxl, release_info_ext);
            break;
        }
        case QXL_CMD_MESSAGE: {
            QXLReleaseInfoExt release_info_ext;
            QXLMessage *message = (QXLMessage *)get_virt(worker, ext_cmd.cmd.data,
                                                         sizeof(QXLMessage), ext_cmd.group_id);
            red_printf("MESSAGE: %s", message->data);
            release_info_ext.group_id = ext_cmd.group_id;
            release_info_ext.info = &message->release_info;
            worker->qxl->release_resource(worker->qxl, release_info_ext);
            break;
        }
        default:
            red_error("bad command type");
        }
        n++;
        if ((worker->display_channel && worker->display_channel->base.send_data.blocked) ||
                                                            red_now() - start > 10 * 1000 * 1000) {
            worker->epoll_timeout = 0;
            return n;
        }
    }
    return n;
}

#define RED_RELEASE_BUNCH_SIZE 5

static void red_free_some(RedWorker *worker)
{
    int n = 0;

    if (worker->display_channel && worker->display_channel->glz_dict) {
        // encoding using the dictionary is prevented since the following operations might
        // change the dictionary
        pthread_rwlock_wrlock(&worker->display_channel->glz_dict->encode_lock);
        n = red_display_free_some_independent_glz_drawables(worker->display_channel);
    }

    while (!ring_is_empty(&worker->current_list) && n++ < RED_RELEASE_BUNCH_SIZE) {
        free_one_drawable(worker, TRUE);
    }

    if (worker->display_channel && worker->display_channel->glz_dict) {
        pthread_rwlock_unlock(&worker->display_channel->glz_dict->encode_lock);
    }
}

static void red_current_flush(RedWorker *worker)
{
    while (!ring_is_empty(&worker->current_list)) {
        free_one_drawable(worker, FALSE);
    }
    red_current_clear(worker);
}

static void red_add_screen_image(RedWorker *worker)
{
    ImageItem *item;
    int stride;
    SpiceRect area;

    if (!worker->display_channel || !worker->surface.context.canvas) {
        return;
    }

    stride = worker->surface.context.width << 2;
    if (!(item = (ImageItem *)malloc(sizeof(ImageItem) +
                                     worker->surface.context.height * stride))) {
        //warn
        return;
    }

    red_pipe_item_init(&item->link, PIPE_ITEM_TYPE_IMAGE);

    item->refs = 1;
    item->pos.x = item->pos.y = 0;
    item->width = worker->surface.context.width;
    item->height = worker->surface.context.height;
    item->stride = stride;
    item->top_down = worker->surface.context.top_down;

    area.top = area.left = 0;
    area.right = worker->surface.context.width;
    area.bottom = worker->surface.context.height;
    worker->draw_funcs.read_pixels(worker->surface.context.canvas, item->data, stride, &area);
    red_pipe_add_image_item(worker, item);
    release_image_item(item);
    display_channel_push(worker);
}

static void inline __add_buf(RedChannel *channel, uint32_t type, void *data, uint32_t size,
                             uint32_t slot_id, uint32_t group_id)
{
    int pos = channel->send_data.n_bufs++;
    ASSERT(pos < MAX_SEND_BUFS);
    channel->send_data.bufs[pos].type = type;
    channel->send_data.bufs[pos].size = size;
    channel->send_data.bufs[pos].data = data;
    channel->send_data.bufs[pos].slot_id = slot_id;
    channel->send_data.bufs[pos].group_id = group_id;
}

static void add_buf(RedChannel *channel, uint32_t type, void *data, uint32_t size,
                    uint32_t slot_id, uint32_t group_id)
{
    __add_buf(channel, type, data, size, slot_id, group_id);
    channel->send_data.header.size += size;
}

static void fill_path(DisplayChannel *display_channel, QXLPHYSICAL *in_path, uint32_t group_id)
{
    RedWorker *worker;
    RedChannel *channel = &display_channel->base;
    int memslot_id;
    worker = channel->worker;
    ASSERT(in_path && *in_path);
    memslot_id  = get_memslot_id(worker, *in_path);
    QXLPath *path = (QXLPath *)get_virt(worker, *in_path, sizeof(QXLPath), group_id);
    *in_path = channel->send_data.header.size;
    add_buf(channel, BUF_TYPE_RAW, &path->data_size, sizeof(UINT32), 0, 0);
    add_buf(channel, BUF_TYPE_CHUNK, &path->chunk, path->data_size, memslot_id, group_id);
}

static void fill_str(DisplayChannel *display_channel, QXLPHYSICAL *in_str, uint32_t group_id)
{
    RedWorker *worker;
    RedChannel *channel = &display_channel->base;
    int memslot_id;
    worker = channel->worker;
    ASSERT(in_str && *in_str);
    memslot_id  = get_memslot_id(worker, *in_str);
    QXLString *str = (QXLString *)get_virt(worker, *in_str, sizeof(QXLString), group_id);
    *in_str = channel->send_data.header.size;
    add_buf(channel, BUF_TYPE_RAW, &str->length, sizeof(UINT32), 0, 0);
    add_buf(channel, BUF_TYPE_CHUNK, &str->chunk, str->data_size, memslot_id, group_id);
}

static inline void fill_rects_clip(RedChannel *channel, QXLPHYSICAL *in_clip, uint32_t group_id)
{
    RedWorker *worker = channel->worker;
    QXLClipRects *clip;
    int memslot_id = get_memslot_id(worker, *in_clip);

    ASSERT(in_clip && *in_clip);
    clip = (QXLClipRects *)get_virt(worker, *in_clip, sizeof(QXLClipRects), group_id);
    *in_clip = channel->send_data.header.size;
    add_buf(channel, BUF_TYPE_RAW, &clip->num_rects, sizeof(UINT32), 0, 0);
    add_buf(channel, BUF_TYPE_CHUNK, &clip->chunk, clip->num_rects * sizeof(SpiceRect), memslot_id,
            group_id);
}

static void fill_base(DisplayChannel *display_channel, SpiceMsgDisplayBase *base, Drawable *drawable,
                      uint32_t size)
{
    RedChannel *channel = &display_channel->base;
    add_buf(channel, BUF_TYPE_RAW, base, size, 0, 0);
    base->box = drawable->qxl_drawable->bbox;
    base->clip = drawable->qxl_drawable->clip;

    if (base->clip.type == SPICE_CLIP_TYPE_RECTS) {
        fill_rects_clip(channel, &base->clip.data, drawable->group_id);
    } else if (base->clip.type == SPICE_CLIP_TYPE_PATH) {
        fill_path(display_channel, &base->clip.data, drawable->group_id);
    }
}

static inline RedImage *alloc_image(DisplayChannel *display_channel)
{
    ASSERT(display_channel->send_data.bitmap_pos < MAX_BITMAPS);
    return &display_channel->send_data.images[display_channel->send_data.bitmap_pos++];
}

/* io_palette is relative address of the palette*/
static inline void fill_palette(DisplayChannel *display_channel, SPICE_ADDRESS *io_palette, UINT8 *flags,
                                uint32_t group_id)
{
    RedChannel *channel = &display_channel->base;
    RedWorker *worker = channel->worker;
    SpicePalette *palette;

    if (!(*io_palette)) {
        return;
    }
    palette = (SpicePalette *)get_virt(worker, *io_palette, sizeof(SpicePalette), group_id);
    if (palette->unique) {
        if (red_palette_cache_find(display_channel, palette->unique)) {
            *flags |= SPICE_BITMAP_FLAGS_PAL_FROM_CACHE;
            *io_palette = palette->unique;
            return;
        }
        if (red_palette_cache_add(display_channel, palette->unique, 1)) {
            *flags |= SPICE_BITMAP_FLAGS_PAL_CACHE_ME;
        }
    }
    *io_palette = channel->send_data.header.size;
    add_buf(channel, BUF_TYPE_RAW, palette,
            sizeof(SpicePalette) + palette->num_ents * sizeof(UINT32), 0, 0);
}

static inline RedCompressBuf *red_display_alloc_compress_buf(DisplayChannel *display_channel)
{
    RedCompressBuf *ret;

    if (display_channel->send_data.free_compress_bufs) {
        ret = display_channel->send_data.free_compress_bufs;
        display_channel->send_data.free_compress_bufs = ret->next;
    } else {
        if (!(ret = malloc(sizeof(*ret)))) {
            return NULL;
        }
    }

    ret->next = display_channel->send_data.used_compress_bufs;
    display_channel->send_data.used_compress_bufs = ret;
    return ret;
}

static inline void __red_display_free_compress_buf(DisplayChannel *display_channel,
                                                   RedCompressBuf *buf)
{
    buf->next = display_channel->send_data.free_compress_bufs;
    display_channel->send_data.free_compress_bufs = buf;
}

static void red_display_free_compress_buf(DisplayChannel *display_channel,
                                          RedCompressBuf *buf)
{
    RedCompressBuf **curr_used = &display_channel->send_data.used_compress_bufs;

    for (;;) {
        ASSERT(*curr_used);
        if (*curr_used == buf) {
            *curr_used = buf->next;
            break;
        }
        curr_used = &(*curr_used)->next;
    }
    __red_display_free_compress_buf(display_channel, buf);
}

static void red_display_reset_compress_buf(DisplayChannel *display_channel)
{
    while (display_channel->send_data.used_compress_bufs) {
        RedCompressBuf *buf = display_channel->send_data.used_compress_bufs;
        display_channel->send_data.used_compress_bufs = buf->next;
        __red_display_free_compress_buf(display_channel, buf);
    }
}

/******************************************************
 *      Global lz red drawables routines
*******************************************************/

/* if already exists, returns it. Otherwise allocates and adds it (1) to the ring tail
   in the channel (2) to the Drawable*/
static RedGlzDrawable *red_display_get_glz_drawable(DisplayChannel *channel, Drawable *drawable)
{
    RedGlzDrawable *ret;

    if (drawable->red_glz_drawable) {
        return drawable->red_glz_drawable;
    }

    if (!(ret = malloc(sizeof(*ret)))) {
        PANIC("malloc failed");
    }

    ret->display_channel = channel;
    ret->qxl_drawable = drawable->qxl_drawable;
    ret->drawable = drawable;
    ret->group_id = drawable->group_id;
    ret->self_bitmap = drawable->self_bitmap;
    ret->instances_count = 0;
    ring_init(&ret->instances);

    ring_item_init(&ret->link);

    ring_add_before(&ret->link, &channel->glz_drawables);
    drawable->red_glz_drawable = ret;

    return ret;
}

/* allocates new instance and adds it to instances in the given drawable.
   NOTE - the caller should set the glz_instance returned by the encoder by itself.*/
static GlzDrawableInstanceItem *red_display_add_glz_drawable_instance(RedGlzDrawable *glz_drawable)
{
    ASSERT(glz_drawable->instances_count < MAX_GLZ_DRAWABLE_INSTANCES);
    // NOTE: We assume the addtions are performed consecutively, without removals in the middle
    GlzDrawableInstanceItem *ret = glz_drawable->instances_pool + glz_drawable->instances_count;
    glz_drawable->instances_count++;

    ring_item_init(&ret->free_link);
    ring_item_init(&ret->glz_link);
    ring_add(&glz_drawable->instances, &ret->glz_link);
    ret->glz_instance = NULL;
    ret->red_glz_drawable = glz_drawable;

    return ret;
}

/* Remove from the to_free list and the instances_list.
   When no instance is left - the RedGlzDrawable is released too. (and the qxl drawblae too, if
   it is not used by Drawable).
   NOTE - 1) can be called only by the display channel that created the drawable
          2) it is assumed that the instance was already removed from the dicitonary*/
static void red_display_free_glz_drawable_instance(DisplayChannel *channel,
                                                   GlzDrawableInstanceItem *glz_drawable_instance)
{
    RedGlzDrawable *glz_drawable;

    ASSERT(glz_drawable_instance);
    ASSERT(glz_drawable_instance->red_glz_drawable);

    glz_drawable = glz_drawable_instance->red_glz_drawable;

    ASSERT(glz_drawable->display_channel == channel);
    ASSERT(glz_drawable->instances_count);

    ring_remove(&glz_drawable_instance->glz_link);
    glz_drawable->instances_count--;
    // whan the remove callback is performed from the channel that the
    // drawable belongs to, the instance is not added to the 'to_free' list
    if (ring_item_is_linked(&glz_drawable_instance->free_link)) {
        ring_remove(&glz_drawable_instance->free_link);
    }

    if (ring_is_empty(&glz_drawable->instances)) {
        ASSERT(!glz_drawable->instances_count);

        Drawable *drawable = glz_drawable->drawable;

        if (drawable) {
            drawable->red_glz_drawable = NULL;
        } else { // no reference to the qxl drawable left
            free_qxl_drawable(channel->base.worker, glz_drawable->qxl_drawable,
                              glz_drawable->group_id, glz_drawable->self_bitmap);
        }

        if (ring_item_is_linked(&glz_drawable->link)) {
            ring_remove(&glz_drawable->link);
        }
        free(glz_drawable);
    }
}

static void red_display_handle_glz_drawables_to_free(DisplayChannel* channel)
{
    RingItem *ring_link;
    pthread_mutex_lock(&channel->glz_drawables_inst_to_free_lock);

    while ((ring_link = ring_get_head(&channel->glz_drawables_inst_to_free))) {
        GlzDrawableInstanceItem *drawable_instance = CONTAINEROF(ring_link,
                                                                 GlzDrawableInstanceItem,
                                                                 free_link);
        red_display_free_glz_drawable_instance(channel, drawable_instance);
    }

    pthread_mutex_unlock(&channel->glz_drawables_inst_to_free_lock);
}

/* releases all the instances of the drawable from the dictionary and the display channel.
   The release of the last instance will also release the drawable itself and the qxl drawable
   if possible.
   NOTE - the caller should prevent encoding using the dicitonary during this operation*/
static void red_display_free_glz_drawable(DisplayChannel *channel, RedGlzDrawable *drawable)
{
    RingItem *head_instance = ring_get_head(&drawable->instances);
    int cont = (head_instance != NULL);

    while (cont) {
        if (drawable->instances_count == 1) {
            /* Last instance: red_display_free_glz_drawable_instance will free the drawable */
            cont = FALSE;
        }
        GlzDrawableInstanceItem *instance = CONTAINEROF(head_instance,
                                                        GlzDrawableInstanceItem,
                                                        glz_link);
        if (!ring_item_is_linked(&instance->free_link)) {
            // the instance didn't get out from window yet
            glz_enc_dictionary_remove_image(channel->glz_dict->dict,
                                            instance->glz_instance,
                                            &channel->glz_data.usr);
        }
        red_display_free_glz_drawable_instance(channel, instance);

        if (cont) {
            head_instance = ring_get_head(&drawable->instances);
        }
    }
}

/* Clear all lz drawables - enforce their removal from the global dictionary.
   NOTE - prevents encoding using the dicitonary during the operation*/
static void red_display_clear_glz_drawables(DisplayChannel *channel)
{
    RingItem *ring_link;

    if (!channel || !channel->glz_dict) {
        return;
    }

    // assure no display channel is during global lz encoding
    pthread_rwlock_wrlock(&channel->glz_dict->encode_lock);

    while ((ring_link = ring_get_head(&channel->glz_drawables))) {
        RedGlzDrawable *drawable = CONTAINEROF(ring_link, RedGlzDrawable, link);
        // no need to lock the to_free list, since we assured no other thread is encoding and
        // thus not other thread access the to_free list of the channel
        red_display_free_glz_drawable(channel, drawable);
    }

    pthread_rwlock_unlock(&channel->glz_dict->encode_lock);
}

/* Remove from the global lz dictionary some glz_drawables that have no reference to
   Drawable (their qxl drawables are released too).
   NOTE - the caller should prevent encoding using the dicitonary during the operation*/
static int red_display_free_some_independent_glz_drawables(DisplayChannel *channel)
{
    int n = 0;

    if (!channel) {
        return 0;
    }

    RingItem *ring_link = ring_get_head(&channel->glz_drawables);

    while ((n < RED_RELEASE_BUNCH_SIZE) && (ring_link != NULL)) {
        RedGlzDrawable *glz_drawable = CONTAINEROF(ring_link, RedGlzDrawable, link);
        ring_link = ring_next(&channel->glz_drawables, ring_link);
        if (!glz_drawable->drawable) {
            red_display_free_glz_drawable(channel, glz_drawable);
            n++;
        }
    }
    return n;
}

/******************************************************
 *              Encoders callbacks
*******************************************************/
static void quic_usr_error(QuicUsrContext *usr, const char *fmt, ...)
{
    EncoderData *usr_data = &(((QuicData *)usr)->data);
    va_list ap;

    va_start(ap, fmt);
    vsnprintf(usr_data->message_buf, sizeof(usr_data->message_buf), fmt, ap);
    va_end(ap);
    red_printf("%s", usr_data->message_buf);

    longjmp(usr_data->jmp_env, 1);
}

static void lz_usr_error(LzUsrContext *usr, const char *fmt, ...)
{
    EncoderData *usr_data = &(((LzData *)usr)->data);
    va_list ap;

    va_start(ap, fmt);
    vsnprintf(usr_data->message_buf, sizeof(usr_data->message_buf), fmt, ap);
    va_end(ap);
    red_printf("%s", usr_data->message_buf);

    longjmp(usr_data->jmp_env, 1);
}

static void glz_usr_error(GlzEncoderUsrContext *usr, const char *fmt, ...)
{
    EncoderData *usr_data = &(((GlzData *)usr)->data);
    va_list ap;

    va_start(ap, fmt);
    vsnprintf(usr_data->message_buf, sizeof(usr_data->message_buf), fmt, ap);
    va_end(ap);

    PANIC("%s", usr_data->message_buf); // if global lz fails in the middle
                                        // the consequences are not predictable since the window
                                        // can turn to be unsynchronized between the server and
                                        // and the client
}

static void quic_usr_warn(QuicUsrContext *usr, const char *fmt, ...)
{
    EncoderData *usr_data = &(((QuicData *)usr)->data);
    va_list ap;

    va_start(ap, fmt);
    vsnprintf(usr_data->message_buf, sizeof(usr_data->message_buf), fmt, ap);
    va_end(ap);
    red_printf("%s", usr_data->message_buf);
}

static void lz_usr_warn(LzUsrContext *usr, const char *fmt, ...)
{
    EncoderData *usr_data = &(((LzData *)usr)->data);
    va_list ap;

    va_start(ap, fmt);
    vsnprintf(usr_data->message_buf, sizeof(usr_data->message_buf), fmt, ap);
    va_end(ap);
    red_printf("%s", usr_data->message_buf);
}

static void glz_usr_warn(GlzEncoderUsrContext *usr, const char *fmt, ...)
{
    EncoderData *usr_data = &(((GlzData *)usr)->data);
    va_list ap;

    va_start(ap, fmt);
    vsnprintf(usr_data->message_buf, sizeof(usr_data->message_buf), fmt, ap);
    va_end(ap);
    red_printf("%s", usr_data->message_buf);
}

static void *quic_usr_malloc(QuicUsrContext *usr, int size)
{
    return malloc(size);
}

static void *lz_usr_malloc(LzUsrContext *usr, int size)
{
    return malloc(size);
}

static void *glz_usr_malloc(GlzEncoderUsrContext *usr, int size)
{
    return malloc(size);
}

static void quic_usr_free(QuicUsrContext *usr, void *ptr)
{
    free(ptr);
}

static void lz_usr_free(LzUsrContext *usr, void *ptr)
{
    free(ptr);
}

static void glz_usr_free(GlzEncoderUsrContext *usr, void *ptr)
{
    free(ptr);
}

static inline int encoder_usr_more_space(EncoderData *enc_data, uint32_t **io_ptr)
{
    RedCompressBuf *buf;

    if (!(buf = red_display_alloc_compress_buf(enc_data->display_channel))) {
        return 0;
    }
    enc_data->bufs_tail->send_next = buf;
    enc_data->bufs_tail = buf;
    buf->send_next = NULL;
    *io_ptr = buf->buf;
    return sizeof(buf->buf) >> 2;
}

static int quic_usr_more_space(QuicUsrContext *usr, uint32_t **io_ptr, int rows_completed)
{
    EncoderData *usr_data = &(((QuicData *)usr)->data);
    return encoder_usr_more_space(usr_data, io_ptr);
}

static int lz_usr_more_space(LzUsrContext *usr, uint8_t **io_ptr)
{
    EncoderData *usr_data = &(((LzData *)usr)->data);
    return (encoder_usr_more_space(usr_data, (uint32_t **)io_ptr) << 2);
}

static int glz_usr_more_space(GlzEncoderUsrContext *usr, uint8_t **io_ptr)
{
    EncoderData *usr_data = &(((GlzData *)usr)->data);
    return (encoder_usr_more_space(usr_data, (uint32_t **)io_ptr) << 2);
}

static inline int encoder_usr_more_lines(EncoderData *enc_data, uint8_t **lines)
{
    uint32_t data_size;
    uint8_t *data;

    if (!enc_data->u.lines_data.next) {
        return 0;
    }

    QXLDataChunk *chunk = (QXLDataChunk *)enc_data->u.lines_data.enc_get_virt(
                          enc_data->u.lines_data.enc_get_virt_opaque, enc_data->u.lines_data.next,
                          sizeof(QXLDataChunk), enc_data->u.lines_data.group_id);

    data_size = chunk->data_size;
    data = chunk->data;

    if (data_size % enc_data->u.lines_data.stride) {
        return 0;
    }

    enc_data->u.lines_data.enc_validate_virt(enc_data->u.lines_data.enc_validate_virt_opaque,
                                             (unsigned long)data, enc_data->u.lines_data.next,
                                             data_size, enc_data->u.lines_data.group_id);

    enc_data->u.lines_data.next = chunk->next_chunk;
    *lines = data;
    return data_size / enc_data->u.lines_data.stride;
}

static int quic_usr_more_lines(QuicUsrContext *usr, uint8_t **lines)
{
    EncoderData *usr_data = &(((QuicData *)usr)->data);
    return encoder_usr_more_lines(usr_data, lines);
}

static int lz_usr_more_lines(LzUsrContext *usr, uint8_t **lines)
{
    EncoderData *usr_data = &(((LzData *)usr)->data);
    return encoder_usr_more_lines(usr_data, lines);
}

static int glz_usr_more_lines(GlzEncoderUsrContext *usr, uint8_t **lines)
{
    EncoderData *usr_data = &(((GlzData *)usr)->data);
    return encoder_usr_more_lines(usr_data, lines);
}

static int quic_usr_more_lines_revers(QuicUsrContext *usr, uint8_t **lines)
{
    uint8_t *data;
    uint32_t data_size;
    EncoderData *quic_data = &(((QuicData *)usr)->data);

    if (!quic_data->u.lines_data.next) {
        return 0;
    }

    QXLDataChunk *chunk = (QXLDataChunk *)quic_data->u.lines_data.enc_get_virt(
                          quic_data->u.lines_data.enc_get_virt_opaque,
                          quic_data->u.lines_data.next,
                          sizeof(QXLDataChunk), quic_data->u.lines_data.group_id);

    data_size = chunk->data_size;
    data = chunk->data;

    if (data_size % quic_data->u.lines_data.stride) {
        return 0;
    }

    quic_data->u.lines_data.enc_validate_virt(quic_data->u.lines_data.enc_validate_virt_opaque,
                                              (unsigned long)data,
                                              quic_data->u.lines_data.next, data_size,
                                              quic_data->u.lines_data.group_id);

    quic_data->u.lines_data.next = chunk->prev_chunk;
    *lines = data + data_size - quic_data->u.lines_data.stride;
    return data_size / quic_data->u.lines_data.stride;
}

static int quic_usr_more_lines_unstable(QuicUsrContext *usr, uint8_t **out_lines)
{
    EncoderData *quic_data = &(((QuicData *)usr)->data);

    if (!quic_data->u.unstable_lines_data.lines) {
        return 0;
    }
    uint8_t *src = quic_data->u.unstable_lines_data.next;
    int lines = MIN(quic_data->u.unstable_lines_data.lines,
                    quic_data->u.unstable_lines_data.max_lines_bunch);
    quic_data->u.unstable_lines_data.lines -= lines;
    uint8_t *end = src + lines * quic_data->u.unstable_lines_data.src_stride;
    quic_data->u.unstable_lines_data.next = end;

    uint8_t *out = (uint8_t *)quic_data->u.unstable_lines_data.input_bufs[
            quic_data->u.unstable_lines_data.input_bufs_pos++ & 1]->buf;
    uint8_t *dest = out;
    for (; src != end; src += quic_data->u.unstable_lines_data.src_stride,
                       dest += quic_data->u.unstable_lines_data.dest_stride) {
        memcpy(dest, src, quic_data->u.unstable_lines_data.dest_stride);
    }
    *out_lines = out;
    return lines;
}

static int quic_usr_no_more_lines(QuicUsrContext *usr, uint8_t **lines)
{
    return 0;
}

static int lz_usr_no_more_lines(LzUsrContext *usr, uint8_t **lines)
{
    return 0;
}

static int glz_usr_no_more_lines(GlzEncoderUsrContext *usr, uint8_t **lines)
{
    return 0;
}

static void glz_usr_free_image(GlzEncoderUsrContext *usr, GlzUsrImageContext *image)
{
    GlzData *lz_data = (GlzData *)usr;
    GlzDrawableInstanceItem *glz_drawable_instance = (GlzDrawableInstanceItem *)image;
    DisplayChannel *drawable_channel = glz_drawable_instance->red_glz_drawable->display_channel;
    DisplayChannel *this_channel = CONTAINEROF(lz_data, DisplayChannel, glz_data);
    if (this_channel == drawable_channel) {
        red_display_free_glz_drawable_instance(drawable_channel, glz_drawable_instance);
    } else {
        pthread_mutex_lock(&drawable_channel->glz_drawables_inst_to_free_lock);
        ring_add_before(&glz_drawable_instance->free_link,
                        &drawable_channel->glz_drawables_inst_to_free);
        pthread_mutex_unlock(&drawable_channel->glz_drawables_inst_to_free_lock);
    }
}

static inline void red_init_quic(RedWorker *worker)
{
    worker->quic_data.usr.error = quic_usr_error;
    worker->quic_data.usr.warn = quic_usr_warn;
    worker->quic_data.usr.info = quic_usr_warn;
    worker->quic_data.usr.malloc = quic_usr_malloc;
    worker->quic_data.usr.free = quic_usr_free;
    worker->quic_data.usr.more_space = quic_usr_more_space;
    worker->quic_data.usr.more_lines = quic_usr_more_lines;

    worker->quic = quic_create(&worker->quic_data.usr);

    if (!worker->quic) {
        PANIC("create quic failed");
    }
}

static inline void red_init_lz(RedWorker *worker)
{
    worker->lz_data.usr.error = lz_usr_error;
    worker->lz_data.usr.warn = lz_usr_warn;
    worker->lz_data.usr.info = lz_usr_warn;
    worker->lz_data.usr.malloc = lz_usr_malloc;
    worker->lz_data.usr.free = lz_usr_free;
    worker->lz_data.usr.more_space = lz_usr_more_space;
    worker->lz_data.usr.more_lines = lz_usr_more_lines;

    worker->lz = lz_create(&worker->lz_data.usr);

    if (!worker->lz) {
        PANIC("create lz failed");
    }
}

static inline void red_display_init_glz_data(DisplayChannel *display)
{
    display->glz_data.usr.error = glz_usr_error;
    display->glz_data.usr.warn = glz_usr_warn;
    display->glz_data.usr.info = glz_usr_warn;
    display->glz_data.usr.malloc = glz_usr_malloc;
    display->glz_data.usr.free = glz_usr_free;
    display->glz_data.usr.more_space = glz_usr_more_space;
    display->glz_data.usr.more_lines = glz_usr_more_lines;
    display->glz_data.usr.free_image = glz_usr_free_image;
}

#ifdef __GNUC__
#define ATTR_PACKED __attribute__ ((__packed__))
#else
#define ATTR_PACKED
#pragma pack(push)
#pragma pack(1)
#endif


typedef struct ATTR_PACKED rgb32_pixel_t {
    uint8_t b;
    uint8_t g;
    uint8_t r;
    uint8_t pad;
} rgb32_pixel_t;

typedef struct ATTR_PACKED rgb24_pixel_t {
    uint8_t b;
    uint8_t g;
    uint8_t r;
} rgb24_pixel_t;

typedef uint16_t rgb16_pixel_t;

#ifndef __GNUC__
#pragma pack(pop)
#endif

#undef ATTR_PACKED

#define RED_BITMAP_UTILS_RGB16
#include "red_bitmap_utils.h"
#define RED_BITMAP_UTILS_RGB24
#include "red_bitmap_utils.h"
#define RED_BITMAP_UTILS_RGB32
#include "red_bitmap_utils.h"

#define GRADUAL_SCORE_RGB24_TH -0.03
#define GRADUAL_SCORE_RGB16_TH 0

// assumes that stride doesn't overflow
static int _bitmap_is_gradual(RedWorker *worker, SpiceBitmap *bitmap, uint32_t group_id)
{
    double score = 0.0;
    int num_samples = 0;

    if ((bitmap->flags & QXL_BITMAP_DIRECT)) {
        uint32_t x;
        uint32_t y;

        x = bitmap->x;
        y = bitmap->y;
        switch (bitmap->format) {
        case SPICE_BITMAP_FMT_16BIT: {
            uint8_t *lines = (uint8_t*)get_virt(worker, bitmap->data, x * y *
                                                sizeof(rgb16_pixel_t), group_id);
            compute_lines_gradual_score_rgb16((rgb16_pixel_t*)lines, x, y, &score, &num_samples);
            break;
        }
        case SPICE_BITMAP_FMT_24BIT: {
            uint8_t *lines = (uint8_t*)get_virt(worker, bitmap->data, x * y *
                                                sizeof(rgb24_pixel_t), group_id);
            compute_lines_gradual_score_rgb24((rgb24_pixel_t*)lines, x, y, &score, &num_samples);
            break;
        }
        case SPICE_BITMAP_FMT_32BIT:
        case SPICE_BITMAP_FMT_RGBA: {
            uint8_t *lines = (uint8_t*)get_virt(worker, bitmap->data, x * y *
                                                sizeof(rgb32_pixel_t), group_id);
            compute_lines_gradual_score_rgb32((rgb32_pixel_t*)lines, x, y, &score, &num_samples);
            break;
        }
        default:
            red_error("invalid bitmap format (not RGB) %u", bitmap->format);
        }
    } else {
        QXLDataChunk *chunk = NULL;
        int num_lines;
        double chunk_score = 0.0;
        int chunk_num_samples = 0;
        uint32_t x;
        SPICE_ADDRESS relative_address = bitmap->data;

        while (relative_address) {
            chunk = (QXLDataChunk *)get_virt(worker, relative_address, sizeof(QXLDataChunk),
                                             group_id);
            num_lines = chunk->data_size / bitmap->stride;
            x = bitmap->x;
            switch (bitmap->format) {
            case SPICE_BITMAP_FMT_16BIT:
                validate_virt(worker, (unsigned long)chunk->data,
                              get_memslot_id(worker, relative_address),
                              sizeof(rgb16_pixel_t) * x * num_lines, group_id);
                compute_lines_gradual_score_rgb16((rgb16_pixel_t*)chunk->data, x, num_lines,
                                                  &chunk_score, &chunk_num_samples);
                break;
            case SPICE_BITMAP_FMT_24BIT:
                validate_virt(worker, (unsigned long)chunk->data,
                              get_memslot_id(worker, relative_address),
                              sizeof(rgb24_pixel_t) * x * num_lines, group_id);
                compute_lines_gradual_score_rgb24((rgb24_pixel_t*)chunk->data, x, num_lines,
                                                  &chunk_score, &chunk_num_samples);
                break;
            case SPICE_BITMAP_FMT_32BIT:
            case SPICE_BITMAP_FMT_RGBA:
                validate_virt(worker, (unsigned long)chunk->data,
                              get_memslot_id(worker, relative_address),
                              sizeof(rgb32_pixel_t) *  x * num_lines, group_id);
                compute_lines_gradual_score_rgb32((rgb32_pixel_t*)chunk->data, x, num_lines,
                                                  &chunk_score, &chunk_num_samples);
                break;
            default:
                red_error("invalid bitmap format (not RGB) %u", bitmap->format);
            }

            score += chunk_score;
            num_samples += chunk_num_samples;

            relative_address = chunk->next_chunk;
        }
    }

    ASSERT(num_samples);
    score /= num_samples;

    if (bitmap->format == SPICE_BITMAP_FMT_16BIT) {
        return (score < GRADUAL_SCORE_RGB16_TH);
    } else {
        return (score < GRADUAL_SCORE_RGB24_TH);
    }
}

static inline int _stride_is_extra(SpiceBitmap *bitmap)
{
    ASSERT(bitmap);
    if (BITMAP_FMT_IS_RGB[bitmap->format]) {
        return ((bitmap->x * BITMAP_FMP_BYTES_PER_PIXEL[bitmap->format]) < bitmap->stride);
    } else {
        switch (bitmap->format) {
        case SPICE_BITMAP_FMT_8BIT:
            return (bitmap->x < bitmap->stride);
        case SPICE_BITMAP_FMT_4BIT_BE:
        case SPICE_BITMAP_FMT_4BIT_LE: {
            int bytes_width = ALIGN(bitmap->x, 2) >> 1;
            return bytes_width < bitmap->stride;
        }
        case SPICE_BITMAP_FMT_1BIT_BE:
        case SPICE_BITMAP_FMT_1BIT_LE: {
            int bytes_width = ALIGN(bitmap->x, 8) >> 3;
            return bytes_width < bitmap->stride;
        }
        default:
            red_error("invalid image type %u", bitmap->format);
        }
    }
}

static const LzImageType MAP_BITMAP_FMT_TO_LZ_IMAGE_TYPE[] = {
    LZ_IMAGE_TYPE_INVALID,
    LZ_IMAGE_TYPE_PLT1_LE,
    LZ_IMAGE_TYPE_PLT1_BE,
    LZ_IMAGE_TYPE_PLT4_LE,
    LZ_IMAGE_TYPE_PLT4_BE,
    LZ_IMAGE_TYPE_PLT8,
    LZ_IMAGE_TYPE_RGB16,
    LZ_IMAGE_TYPE_RGB24,
    LZ_IMAGE_TYPE_RGB32,
    LZ_IMAGE_TYPE_RGBA
};

typedef struct compress_send_data_t {
    uint32_t raw_size;
    void*    comp_buf;
    uint32_t comp_buf_size;
    SPICE_ADDRESS  *plt_ptr;
    UINT8    *flags_ptr;
} compress_send_data_t;


static inline int red_glz_compress_image(DisplayChannel *display_channel,
                                         RedImage *dest, SpiceBitmap *src, Drawable *drawable,
                                         compress_send_data_t* o_comp_data)
{
    RedWorker *worker = (RedWorker *)display_channel->base.worker;
#ifdef COMPRESS_STAT
    stat_time_t start_time = stat_now();
#endif
    ASSERT(BITMAP_FMT_IS_RGB[src->format]);
    GlzData *glz_data = &display_channel->glz_data;
    LzImageType type = MAP_BITMAP_FMT_TO_LZ_IMAGE_TYPE[src->format];
    RedGlzDrawable *glz_drawable;
    GlzDrawableInstanceItem *glz_drawable_instance;
    uint8_t *lines;
    unsigned int num_lines;
    int size;

    glz_data->data.bufs_tail = red_display_alloc_compress_buf(display_channel);
    glz_data->data.bufs_head = glz_data->data.bufs_tail;

    if (!glz_data->data.bufs_head) {
        return FALSE;
    }

    glz_data->data.bufs_head->send_next = NULL;
    glz_data->data.display_channel = display_channel;

    glz_drawable = red_display_get_glz_drawable(display_channel, drawable);
    glz_drawable_instance = red_display_add_glz_drawable_instance(glz_drawable);

    if ((src->flags & QXL_BITMAP_DIRECT)) {
        glz_data->usr.more_lines = glz_usr_no_more_lines;
        lines = (uint8_t*)get_virt(worker, src->data, src->stride * src->y, drawable->group_id);
        num_lines = src->y;
    } else {
        glz_data->data.u.lines_data.enc_get_virt = cb_get_virt;
        glz_data->data.u.lines_data.enc_get_virt_opaque = worker;
        glz_data->data.u.lines_data.enc_validate_virt = cb_validate_virt;
        glz_data->data.u.lines_data.enc_validate_virt_opaque = worker;
        glz_data->data.u.lines_data.stride = src->stride;
        glz_data->data.u.lines_data.next = src->data;
        glz_data->data.u.lines_data.group_id = drawable->group_id;
        glz_data->usr.more_lines = glz_usr_more_lines;
        lines = NULL;
        num_lines = 0;
    }

    size = glz_encode(display_channel->glz, type, src->x, src->y,
                      (src->flags & QXL_BITMAP_TOP_DOWN), lines, num_lines,
                      src->stride, (uint8_t*)glz_data->data.bufs_head->buf,
                      sizeof(glz_data->data.bufs_head->buf),
                      glz_drawable_instance,
                      &glz_drawable_instance->glz_instance);

    dest->descriptor.type = SPICE_IMAGE_TYPE_GLZ_RGB;
    dest->lz_rgb.data_size = size;

    o_comp_data->raw_size = sizeof(SpiceLZRGBImage);
    o_comp_data->comp_buf = glz_data->data.bufs_head;
    o_comp_data->comp_buf_size = size;
    o_comp_data->plt_ptr = NULL;
    o_comp_data->flags_ptr = NULL;

    stat_compress_add(&display_channel->glz_stat, start_time, src->stride * src->y,
                      o_comp_data->comp_buf_size);
    return TRUE;
}

static inline int red_lz_compress_image(DisplayChannel *display_channel,
                                        RedImage *dest, SpiceBitmap *src,
                                        compress_send_data_t* o_comp_data, uint32_t group_id)
{
    RedWorker *worker = display_channel->base.worker;
    LzData *lz_data = &worker->lz_data;
    LzContext *lz = worker->lz;
    LzImageType type = MAP_BITMAP_FMT_TO_LZ_IMAGE_TYPE[src->format];
    int size;            // size of the compressed data

#ifdef COMPRESS_STAT
    stat_time_t start_time = stat_now();
#endif

    lz_data->data.bufs_tail = red_display_alloc_compress_buf(display_channel);
    lz_data->data.bufs_head = lz_data->data.bufs_tail;

    if (!lz_data->data.bufs_head) {
        return FALSE;
    }

    lz_data->data.bufs_head->send_next = NULL;
    lz_data->data.display_channel = display_channel;

    if (setjmp(lz_data->data.jmp_env)) {
        while (lz_data->data.bufs_head) {
            RedCompressBuf *buf = lz_data->data.bufs_head;
            lz_data->data.bufs_head = buf->send_next;
            red_display_free_compress_buf(display_channel, buf);
        }
        return FALSE;
    }

    if ((src->flags & QXL_BITMAP_DIRECT)) {
        lz_data->usr.more_lines = lz_usr_no_more_lines;
        size = lz_encode(lz, type, src->x, src->y, (src->flags & QXL_BITMAP_TOP_DOWN),
                         (uint8_t*)get_virt(worker, src->data, src->stride * src->y, group_id),
                         src->y, src->stride, (uint8_t*)lz_data->data.bufs_head->buf,
                         sizeof(lz_data->data.bufs_head->buf));
    } else {
        lz_data->data.u.lines_data.enc_get_virt = cb_get_virt;
        lz_data->data.u.lines_data.enc_get_virt_opaque = worker;
        lz_data->data.u.lines_data.enc_validate_virt = cb_validate_virt;
        lz_data->data.u.lines_data.enc_validate_virt_opaque = worker;
        lz_data->data.u.lines_data.stride = src->stride;
        lz_data->data.u.lines_data.next = src->data;
        lz_data->data.u.lines_data.group_id = group_id;
        lz_data->usr.more_lines = lz_usr_more_lines;

        size = lz_encode(lz, type, src->x, src->y, (src->flags & QXL_BITMAP_TOP_DOWN),
                         NULL, 0, src->stride,
                         (uint8_t*)lz_data->data.bufs_head->buf,
                         sizeof(lz_data->data.bufs_head->buf));
    }

    // the compressed buffer is bigger than the original data
    if (size > (src->y * src->stride)) {
        longjmp(lz_data->data.jmp_env, 1);
    }

    if (BITMAP_FMT_IS_RGB[src->format]) {
        dest->descriptor.type = SPICE_IMAGE_TYPE_LZ_RGB;
        dest->lz_rgb.data_size = size;

        o_comp_data->raw_size = sizeof(SpiceLZRGBImage);
        o_comp_data->comp_buf = lz_data->data.bufs_head;
        o_comp_data->comp_buf_size = size;
        o_comp_data->plt_ptr = NULL;
        o_comp_data->flags_ptr = NULL;
    } else {
        dest->descriptor.type = SPICE_IMAGE_TYPE_LZ_PLT;
        dest->lz_plt.data_size = size;
        dest->lz_plt.flags = src->flags & SPICE_BITMAP_FLAGS_TOP_DOWN;
        dest->lz_plt.palette = src->palette;

        o_comp_data->raw_size = sizeof(SpiceLZPLTImage);
        o_comp_data->comp_buf = lz_data->data.bufs_head;
        o_comp_data->comp_buf_size = size;
        o_comp_data->plt_ptr = &(dest->lz_plt.palette);
        o_comp_data->flags_ptr = &(dest->lz_plt.flags);
    }
    stat_compress_add(&display_channel->lz_stat, start_time, src->stride * src->y,
                      o_comp_data->comp_buf_size);
    return TRUE;
}

static inline int red_quic_compress_image(DisplayChannel *display_channel, RedImage *dest,
                                          SpiceBitmap *src, compress_send_data_t* o_comp_data,
                                          uint32_t group_id)
{
    RedWorker *worker = display_channel->base.worker;
    QuicData *quic_data = &worker->quic_data;
    QuicContext *quic = worker->quic;
    QuicImageType type;
    int size;

#ifdef COMPRESS_STAT
    stat_time_t start_time = stat_now();
#endif

    switch (src->format) {
    case SPICE_BITMAP_FMT_32BIT:
        type = QUIC_IMAGE_TYPE_RGB32;
        break;
    case SPICE_BITMAP_FMT_RGBA:
        type = QUIC_IMAGE_TYPE_RGBA;
        break;
    case SPICE_BITMAP_FMT_16BIT:
        type = QUIC_IMAGE_TYPE_RGB16;
        break;
    case SPICE_BITMAP_FMT_24BIT:
        type = QUIC_IMAGE_TYPE_RGB24;
        break;
    default:
        return FALSE;
    }

    quic_data->data.bufs_tail = red_display_alloc_compress_buf(display_channel);
    quic_data->data.bufs_head = quic_data->data.bufs_tail;

    if (!quic_data->data.bufs_head) {
        return FALSE;
    }

    quic_data->data.bufs_head->send_next = NULL;
    quic_data->data.display_channel = display_channel;

    if (setjmp(quic_data->data.jmp_env)) {
        while (quic_data->data.bufs_head) {
            RedCompressBuf *buf = quic_data->data.bufs_head;
            quic_data->data.bufs_head = buf->send_next;
            red_display_free_compress_buf(display_channel, buf);
        }
        return FALSE;
    }

    if ((src->flags & QXL_BITMAP_DIRECT)) {
        int stride;
        uint8_t *data;

        if (!(src->flags & QXL_BITMAP_TOP_DOWN)) {
            data = (uint8_t*)get_virt(worker, src->data, src->stride * src->y, group_id) +
                   src->stride * (src->y - 1);
            stride = -src->stride;
        } else {
            data = (uint8_t*)get_virt(worker, src->data, src->stride * src->y, group_id);
            stride = src->stride;
        }

        if ((src->flags & QXL_BITMAP_UNSTABLE)) {
            quic_data->data.u.unstable_lines_data.next = data;
            quic_data->data.u.unstable_lines_data.src_stride = stride;
            quic_data->data.u.unstable_lines_data.dest_stride = src->stride;
            quic_data->data.u.unstable_lines_data.lines = src->y;
            quic_data->data.u.unstable_lines_data.input_bufs_pos = 0;
            if (!(quic_data->data.u.unstable_lines_data.input_bufs[0] =
                                            red_display_alloc_compress_buf(display_channel)) ||
                !(quic_data->data.u.unstable_lines_data.input_bufs[1] =
                                            red_display_alloc_compress_buf(display_channel))) {
                return FALSE;
            }
            quic_data->data.u.unstable_lines_data.max_lines_bunch =
                                 sizeof(quic_data->data.u.unstable_lines_data.input_bufs[0]->buf) /
                                 quic_data->data.u.unstable_lines_data.dest_stride;
            quic_data->usr.more_lines = quic_usr_more_lines_unstable;
            size = quic_encode(quic, type, src->x, src->y, NULL, 0, src->stride,
                               quic_data->data.bufs_head->buf,
                               sizeof(quic_data->data.bufs_head->buf) >> 2);
        } else {
            quic_data->usr.more_lines = quic_usr_no_more_lines;
            size = quic_encode(quic, type, src->x, src->y, data, src->y, stride,
                               quic_data->data.bufs_head->buf,
                               sizeof(quic_data->data.bufs_head->buf) >> 2);
        }
    } else {
        int stride;

        if ((src->flags & QXL_BITMAP_UNSTABLE)) {
            red_printf_once("unexpected unstable bitmap");
            return FALSE;
        }
        quic_data->data.u.lines_data.enc_get_virt = cb_get_virt;
        quic_data->data.u.lines_data.enc_get_virt_opaque = worker;
        quic_data->data.u.lines_data.enc_validate_virt = cb_validate_virt;
        quic_data->data.u.lines_data.enc_validate_virt_opaque = worker;
        quic_data->data.u.lines_data.stride = src->stride;
        quic_data->data.u.lines_data.group_id = group_id;

        if ((src->flags & QXL_BITMAP_TOP_DOWN)) {
            quic_data->data.u.lines_data.next = src->data;
            quic_data->usr.more_lines = quic_usr_more_lines;
            stride = src->stride;
        } else {
            SPICE_ADDRESS prev_addr = src->data;
            QXLDataChunk *chunk = (QXLDataChunk *)get_virt(worker, src->data,
                                                           sizeof(QXLDataChunk), group_id);
            while (chunk->next_chunk) {
                prev_addr = chunk->next_chunk;
                chunk = (QXLDataChunk *)get_virt(worker, chunk->next_chunk, sizeof(QXLDataChunk),
                                                 group_id);
                ASSERT(chunk->prev_chunk);
            }
            quic_data->data.u.lines_data.next = (SPICE_ADDRESS)prev_addr -
                                                get_virt_delta(worker,
                                                               get_memslot_id(worker, src->data),
                                                               group_id);
            quic_data->usr.more_lines = quic_usr_more_lines_revers;
            stride = -src->stride;
        }
        size = quic_encode(quic, type, src->x, src->y, NULL, 0, stride,
                           quic_data->data.bufs_head->buf,
                           sizeof(quic_data->data.bufs_head->buf) >> 2);
    }

    // the compressed buffer is bigger than the original data
    if ((size << 2) > (src->y * src->stride)) {
        longjmp(quic_data->data.jmp_env, 1);
    }

    dest->descriptor.type = SPICE_IMAGE_TYPE_QUIC;
    dest->quic.data_size = size << 2;

    o_comp_data->raw_size = sizeof(SpiceQUICImage);
    o_comp_data->comp_buf = quic_data->data.bufs_head;
    o_comp_data->comp_buf_size = size << 2;
    o_comp_data->plt_ptr = NULL;
    o_comp_data->flags_ptr = NULL;

    stat_compress_add(&display_channel->quic_stat, start_time, src->stride * src->y,
                      o_comp_data->comp_buf_size);
    return TRUE;
}

#define MIN_SIZE_TO_COMPRESS 54
#define MIN_DIMENSION_TO_QUIC 3
static inline int red_compress_image(DisplayChannel *display_channel,
                                     RedImage *dest, SpiceBitmap *src, Drawable *drawable,
                                     compress_send_data_t* o_comp_data)
{
    image_compression_t image_compression = display_channel->base.worker->image_compression;
    int quic_compress = FALSE;

    if ((image_compression == IMAGE_COMPRESS_OFF) ||
        ((src->y * src->stride) < MIN_SIZE_TO_COMPRESS)) { // TODO: change the size cond
        return FALSE;
    } else if (image_compression == IMAGE_COMPRESS_QUIC) {
        if (BITMAP_FMT_IS_PLT[src->format]) {
            return FALSE;
        } else {
            quic_compress = TRUE;
        }
    } else {
        /*
            lz doesn't handle (1) bitmaps with strides that are larger than the width
            of the image in bytes (2) unstable bitmaps
        */
        if (_stride_is_extra(src) || (src->flags & QXL_BITMAP_UNSTABLE)) {
            if ((image_compression == IMAGE_COMPRESS_LZ) ||
                (image_compression == IMAGE_COMPRESS_GLZ) ||
                BITMAP_FMT_IS_PLT[src->format]) {
                return FALSE;
            } else {
                quic_compress = TRUE;
            }
        } else {
            if ((image_compression == IMAGE_COMPRESS_AUTO_LZ) ||
                (image_compression == IMAGE_COMPRESS_AUTO_GLZ)) {
                if ((src->x < MIN_DIMENSION_TO_QUIC) || (src->y < MIN_DIMENSION_TO_QUIC)) {
                    quic_compress = FALSE;
                } else {
                    if (drawable->copy_bitmap_graduality == BITMAP_GRADUAL_INVALID) {
                        quic_compress = BITMAP_FMT_IS_RGB[src->format] &&
                            _bitmap_is_gradual(display_channel->base.worker, src,
                                               drawable->group_id);
                    } else {
                        quic_compress = (drawable->copy_bitmap_graduality == BITMAP_GRADUAL_TRUE);
                    }
                }
            } else {
                quic_compress = FALSE;
            }
        }
    }

    if (quic_compress) {
#ifdef COMPRESS_DEBUG
        red_printf("QUIC compress");
#endif
        return red_quic_compress_image(display_channel, dest, src, o_comp_data, drawable->group_id);
    } else {
        int glz;
        int ret;
        if ((image_compression == IMAGE_COMPRESS_AUTO_GLZ) ||
            (image_compression == IMAGE_COMPRESS_GLZ)) {
            glz = BITMAP_FMT_IS_RGB[src->format] && (
                    (src->x * src->y) < glz_enc_dictionary_get_size(
                        display_channel->glz_dict->dict));
        } else if ((image_compression == IMAGE_COMPRESS_AUTO_LZ) ||
                   (image_compression == IMAGE_COMPRESS_LZ)) {
            glz = FALSE;
        } else {
            red_error("invalid image compression type %u", image_compression);
        }

        if (glz) {
            /* using the global dictionary only if it is not freezed */
            pthread_rwlock_rdlock(&display_channel->glz_dict->encode_lock);
            if (!display_channel->glz_dict->migrate_freeze) {
                ret = red_glz_compress_image(
                        display_channel, dest, src, drawable, o_comp_data);
            } else {
                glz = FALSE;
            }
            pthread_rwlock_unlock(&display_channel->glz_dict->encode_lock);
        }

        if (!glz) {
            ret = red_lz_compress_image(display_channel, dest, src, o_comp_data,
                                        drawable->group_id);
#ifdef COMPRESS_DEBUG
            red_printf("LZ LOCAL compress");
#endif
        }
#ifdef COMPRESS_DEBUG
        else {
            red_printf("LZ global compress fmt=%d", src->format);
        }
#endif
        return ret;
    }
}

static inline void red_display_add_image_to_pixmap_cache(DisplayChannel *display_channel,
                                                         QXLImage *qxl_image, RedImage *io_image)
{
    if ((qxl_image->descriptor.flags & QXL_IMAGE_CACHE)) {
        ASSERT(qxl_image->descriptor.width * qxl_image->descriptor.height > 0);
        if (pixmap_cache_add(display_channel->pixmap_cache, qxl_image->descriptor.id,
                             qxl_image->descriptor.width * qxl_image->descriptor.height,
                             display_channel)) {
            io_image->descriptor.flags |= SPICE_IMAGE_FLAGS_CACHE_ME;
            stat_inc_counter(display_channel->add_to_cache_counter, 1);
        }
    }

    if (!(io_image->descriptor.flags & SPICE_IMAGE_FLAGS_CACHE_ME)) {
        stat_inc_counter(display_channel->non_cache_counter, 1);
    }
}

/* if the number of times fill_bits can be called per one qxl_drawable increases -
   MAX_LZ_DRAWABLE_INSTANCES must be increased as well */
static void fill_bits(DisplayChannel *display_channel, QXLPHYSICAL *in_bitmap, Drawable *drawable)
{
    RedChannel *channel = &display_channel->base;
    RedWorker *worker = channel->worker;
    RedImage *image;
    QXLImage *qxl_image;
    uint8_t *data;
    int memslot_id;
    compress_send_data_t comp_send_data;

    ASSERT(*in_bitmap);

    image = alloc_image(display_channel);
    qxl_image = (QXLImage *)get_virt(worker, *in_bitmap, sizeof(QXLImage), drawable->group_id);

    image->descriptor.id = qxl_image->descriptor.id;
    image->descriptor.type = qxl_image->descriptor.type;
    image->descriptor.flags = 0;
    image->descriptor.width = qxl_image->descriptor.width;
    image->descriptor.height = qxl_image->descriptor.height;

    memslot_id = get_memslot_id(worker, *in_bitmap);
    *in_bitmap = channel->send_data.header.size;
    if ((qxl_image->descriptor.flags & QXL_IMAGE_CACHE)) {
        if (pixmap_cache_hit(display_channel->pixmap_cache, image->descriptor.id,
                             display_channel)) {
            image->descriptor.type = SPICE_IMAGE_TYPE_FROM_CACHE;
            add_buf(channel, BUF_TYPE_RAW, image, sizeof(SpiceImageDescriptor), 0, 0);
            stat_inc_counter(display_channel->cache_hits_counter, 1);
            return;
        }
    }

    switch (qxl_image->descriptor.type) {
    case SPICE_IMAGE_TYPE_BITMAP:
#ifdef DUMP_BITMAP
        dump_bitmap(display_channel->base.worker, &qxl_image->bitmap, drawable->group_id);
#endif
        /* Images must be added to the cache only after they are compressed
           in order to prevent starvation in the client between pixmap_cache and
           global dictionary (in cases of multiple monitors) */
        if (!red_compress_image(display_channel, image, &qxl_image->bitmap,
                                drawable, &comp_send_data)) {
            uint32_t y;
            uint32_t stride;
            SPICE_ADDRESS image_data;

            red_display_add_image_to_pixmap_cache(display_channel, qxl_image, image);

            image->bitmap = qxl_image->bitmap;
            y = image->bitmap.y;
            stride = image->bitmap.stride;
            image_data = image->bitmap.data;
            image->bitmap.flags = image->bitmap.flags & SPICE_BITMAP_FLAGS_TOP_DOWN;

            add_buf(channel, BUF_TYPE_RAW, image, sizeof(SpiceBitmapImage), 0, 0);
            fill_palette(display_channel, &(image->bitmap.palette), &(image->bitmap.flags),
                         drawable->group_id);
            image->bitmap.data = channel->send_data.header.size;
            if (qxl_image->bitmap.flags & QXL_BITMAP_DIRECT) {
                data = (uint8_t *)get_virt(worker, image_data, stride * y, drawable->group_id);
                add_buf(channel, BUF_TYPE_RAW, data, y * stride, 0, 0);
            } else {
                data = (uint8_t *)get_virt(worker, image_data, sizeof(QXLDataChunk),
                                           drawable->group_id);
                add_buf(channel, BUF_TYPE_CHUNK, data, y * stride, memslot_id, drawable->group_id);
            }
        } else {
            red_display_add_image_to_pixmap_cache(display_channel, qxl_image, image);

            add_buf((RedChannel *)display_channel, BUF_TYPE_RAW, image, comp_send_data.raw_size,
                    0, 0);
            add_buf((RedChannel *)display_channel, BUF_TYPE_COMPRESS_BUF,
                    comp_send_data.comp_buf, comp_send_data.comp_buf_size, 0, 0);

            if (comp_send_data.plt_ptr != NULL) {
                fill_palette(display_channel, comp_send_data.plt_ptr, comp_send_data.flags_ptr,
                             drawable->group_id);
            }
        }
        break;
    case SPICE_IMAGE_TYPE_QUIC:
        red_display_add_image_to_pixmap_cache(display_channel, qxl_image, image);
        image->quic = qxl_image->quic;
        add_buf(channel, BUF_TYPE_RAW, image, sizeof(SpiceQUICImage), 0, 0);
        add_buf(channel, BUF_TYPE_CHUNK, qxl_image->quic.data, qxl_image->quic.data_size,
                memslot_id, drawable->group_id);
        break;
    default:
        red_error("invalid image type %u", image->descriptor.type);
    }
}

static void fill_brush(DisplayChannel *display_channel, SpiceBrush *brush, Drawable *drawable)
{
    if (brush->type == SPICE_BRUSH_TYPE_PATTERN) {
        fill_bits(display_channel, &brush->u.pattern.pat, drawable);
    }
}

static void fill_mask(DisplayChannel *display_channel, SpiceQMask *mask, Drawable *drawable)
{
    if (mask->bitmap) {
        if (display_channel->base.worker->image_compression != IMAGE_COMPRESS_OFF) {
            image_compression_t save_img_comp = display_channel->base.worker->image_compression;
            display_channel->base.worker->image_compression = IMAGE_COMPRESS_OFF;
            fill_bits(display_channel, &mask->bitmap, drawable);
            display_channel->base.worker->image_compression = save_img_comp;
        } else {
            fill_bits(display_channel, &mask->bitmap, drawable);
        }
    }
}

static void fill_attr(DisplayChannel *display_channel, SpiceLineAttr *attr, uint32_t group_id)
{
    if (attr->style_nseg) {
        RedChannel *channel = &display_channel->base;
        uint8_t *buf = (uint8_t *)get_virt(channel->worker, attr->style,
                                           attr->style_nseg * sizeof(uint32_t), group_id);
        ASSERT(attr->style);
        attr->style = channel->send_data.header.size;
        add_buf(channel, BUF_TYPE_RAW, buf, attr->style_nseg * sizeof(uint32_t), 0, 0);
    }
}

static void fill_cursor(CursorChannel *cursor_channel, SpiceCursor *red_cursor, CursorItem *cursor)
{
    RedChannel *channel = &cursor_channel->base;

    if (!cursor) {
        red_cursor->flags = SPICE_CURSOR_FLAGS_NONE;
        return;
    }

    if (cursor->type == CURSOR_TYPE_DEV) {
        QXLCursorCmd *cursor_cmd;
        QXLCursor *qxl_cursor;

        cursor_cmd = cursor->qxl_cursor;
        qxl_cursor = (QXLCursor *)get_virt(channel->worker, cursor_cmd->u.set.shape,
                                           sizeof(QXLCursor), cursor->group_id);
        red_cursor->flags = 0;
        red_cursor->header = qxl_cursor->header;

        if (red_cursor->header.unique) {
            if (red_cursor_cache_find(cursor_channel, red_cursor->header.unique)) {
                red_cursor->flags |= SPICE_CURSOR_FLAGS_FROM_CACHE;
                return;
            }
            if (red_cursor_cache_add(cursor_channel, red_cursor->header.unique, 1)) {
                red_cursor->flags |= SPICE_CURSOR_FLAGS_CACHE_ME;
            }
        }

        if (qxl_cursor->data_size) {
            add_buf(channel, BUF_TYPE_CHUNK, &qxl_cursor->chunk, qxl_cursor->data_size,
                    get_memslot_id(channel->worker, cursor_cmd->u.set.shape), cursor->group_id);
        }
    } else {
        LocalCursor *local_cursor;
        ASSERT(cursor->type == CURSOR_TYPE_LOCAL);
        local_cursor = (LocalCursor *)cursor;
        *red_cursor = local_cursor->red_cursor;
        add_buf(channel, BUF_TYPE_RAW, local_cursor->red_cursor.data, local_cursor->data_size, 0,
                0);
    }
}

static inline void red_channel_reset_send_data(RedChannel *channel)
{
    channel->send_data.pos = 0;
    channel->send_data.n_bufs = 1;
    channel->send_data.header.size = 0;
    channel->send_data.header.sub_list = 0;
    ++channel->send_data.header.serial;
    channel->send_data.bufs[0].type = BUF_TYPE_RAW;
    channel->send_data.bufs[0].size = sizeof(SpiceDataHeader);
    channel->send_data.bufs[0].data = (void *)&channel->send_data.header;
}

static inline void red_display_reset_send_data(DisplayChannel *channel)
{
    red_channel_reset_send_data((RedChannel *)channel);
    channel->send_data.bitmap_pos = 0;
    red_display_reset_compress_buf(channel);
    channel->send_data.free_list.res->count = 0;
    memset(channel->send_data.free_list.sync, 0, sizeof(channel->send_data.free_list.sync));
}

static inline void red_send_qxl_drawable(RedWorker *worker, DisplayChannel *display_channel,
                                         Drawable *item)
{
    QXLDrawable *drawable = item->qxl_drawable;

    RedChannel *channel = &display_channel->base;
    switch (drawable->type) {
    case QXL_DRAW_FILL:
        channel->send_data.header.type = SPICE_MSG_DISPLAY_DRAW_FILL;
        fill_base(display_channel, &display_channel->send_data.u.fill.base, item,
                  sizeof(SpiceMsgDisplayDrawFill));
        display_channel->send_data.u.fill.data = drawable->u.fill;
        fill_brush(display_channel, &display_channel->send_data.u.fill.data.brush, item);
        fill_mask(display_channel, &display_channel->send_data.u.fill.data.mask, item);
        break;
    case QXL_DRAW_OPAQUE:
        channel->send_data.header.type = SPICE_MSG_DISPLAY_DRAW_OPAQUE;
        fill_base(display_channel, &display_channel->send_data.u.opaque.base, item,
                  sizeof(SpiceMsgDisplayDrawOpaque));
        display_channel->send_data.u.opaque.data = drawable->u.opaque;
        fill_bits(display_channel, &display_channel->send_data.u.opaque.data.src_bitmap, item);
        fill_brush(display_channel, &display_channel->send_data.u.opaque.data.brush, item);
        fill_mask(display_channel, &display_channel->send_data.u.opaque.data.mask, item);
        break;
    case QXL_DRAW_COPY:
        channel->send_data.header.type = SPICE_MSG_DISPLAY_DRAW_COPY;
        fill_base(display_channel, &display_channel->send_data.u.copy.base, item, sizeof(SpiceMsgDisplayDrawCopy));
        display_channel->send_data.u.copy.data = drawable->u.copy;
        fill_bits(display_channel, &display_channel->send_data.u.copy.data.src_bitmap, item);
        fill_mask(display_channel, &display_channel->send_data.u.copy.data.mask, item);
        break;
    case QXL_DRAW_TRANSPARENT:
        channel->send_data.header.type = SPICE_MSG_DISPLAY_DRAW_TRANSPARENT;
        fill_base(display_channel, &display_channel->send_data.u.transparent.base, item,
                  sizeof(SpiceMsgDisplayDrawTransparent));
        display_channel->send_data.u.transparent.data = drawable->u.transparent;
        fill_bits(display_channel, &display_channel->send_data.u.transparent.data.src_bitmap, item);
        break;
    case QXL_DRAW_ALPHA_BLEND:
        channel->send_data.header.type = SPICE_MSG_DISPLAY_DRAW_ALPHA_BLEND;
        fill_base(display_channel, &display_channel->send_data.u.alpha_blend.base, item,
                  sizeof(SpiceMsgDisplayDrawAlphaBlend));
        display_channel->send_data.u.alpha_blend.data = drawable->u.alpha_blend;
        fill_bits(display_channel, &display_channel->send_data.u.alpha_blend.data.src_bitmap, item);
        break;
    case QXL_COPY_BITS:
        channel->send_data.header.type = SPICE_MSG_DISPLAY_COPY_BITS;
        fill_base(display_channel, &display_channel->send_data.u.copy_bits.base, item,
                  sizeof(SpiceMsgDisplayCopyBits));
        display_channel->send_data.u.copy_bits.src_pos = drawable->u.copy_bits.src_pos;
        break;
    case QXL_DRAW_BLEND:
        channel->send_data.header.type = SPICE_MSG_DISPLAY_DRAW_BLEND;
        fill_base(display_channel, &display_channel->send_data.u.blend.base, item,
                  sizeof(SpiceMsgDisplayDrawBlend));
        display_channel->send_data.u.blend.data = drawable->u.blend;
        fill_bits(display_channel, &display_channel->send_data.u.blend.data.src_bitmap, item);
        fill_mask(display_channel, &display_channel->send_data.u.blend.data.mask, item);
        break;
    case QXL_DRAW_BLACKNESS:
        channel->send_data.header.type = SPICE_MSG_DISPLAY_DRAW_BLACKNESS;
        fill_base(display_channel, &display_channel->send_data.u.blackness.base, item,
                  sizeof(SpiceMsgDisplayDrawBlackness));
        display_channel->send_data.u.blackness.data = drawable->u.blackness;
        fill_mask(display_channel, &display_channel->send_data.u.blackness.data.mask, item);
        break;
    case QXL_DRAW_WHITENESS:
        channel->send_data.header.type = SPICE_MSG_DISPLAY_DRAW_WHITENESS;
        fill_base(display_channel, &display_channel->send_data.u.whiteness.base, item,
                  sizeof(SpiceMsgDisplayDrawWhiteness));
        display_channel->send_data.u.whiteness.data = drawable->u.whiteness;
        fill_mask(display_channel, &display_channel->send_data.u.whiteness.data.mask, item);
        break;
    case QXL_DRAW_INVERS:
        channel->send_data.header.type = SPICE_MSG_DISPLAY_DRAW_INVERS;
        fill_base(display_channel, &display_channel->send_data.u.invers.base, item,
                  sizeof(SpiceMsgDisplayDrawInvers));
        display_channel->send_data.u.invers.data = drawable->u.invers;
        fill_mask(display_channel, &display_channel->send_data.u.invers.data.mask, item);
        break;
    case QXL_DRAW_ROP3:
        channel->send_data.header.type = SPICE_MSG_DISPLAY_DRAW_ROP3;
        fill_base(display_channel, &display_channel->send_data.u.rop3.base, item,
                  sizeof(SpiceMsgDisplayDrawRop3));
        display_channel->send_data.u.rop3.data = drawable->u.rop3;
        fill_bits(display_channel, &display_channel->send_data.u.rop3.data.src_bitmap, item);
        fill_brush(display_channel, &display_channel->send_data.u.rop3.data.brush, item);
        fill_mask(display_channel, &display_channel->send_data.u.rop3.data.mask, item);
        break;
    case QXL_DRAW_STROKE:
        channel->send_data.header.type = SPICE_MSG_DISPLAY_DRAW_STROKE;
        fill_base(display_channel, &display_channel->send_data.u.stroke.base, item,
                  sizeof(SpiceMsgDisplayDrawStroke));
        display_channel->send_data.u.stroke.data = drawable->u.stroke;
        fill_path(display_channel, &display_channel->send_data.u.stroke.data.path, item->group_id);
        fill_attr(display_channel, &display_channel->send_data.u.stroke.data.attr, item->group_id);
        fill_brush(display_channel, &display_channel->send_data.u.stroke.data.brush, item);
        break;
    case QXL_DRAW_TEXT:
        channel->send_data.header.type = SPICE_MSG_DISPLAY_DRAW_TEXT;
        fill_base(display_channel, &display_channel->send_data.u.text.base, item, sizeof(SpiceMsgDisplayDrawText));
        display_channel->send_data.u.text.data = drawable->u.text;
        fill_brush(display_channel, &display_channel->send_data.u.text.data.fore_brush, item);
        fill_brush(display_channel, &display_channel->send_data.u.text.data.back_brush, item);
        fill_str(display_channel, &display_channel->send_data.u.text.data.str, item->group_id);
        break;
    default:
        red_error("invalid type");
    }
    display_begin_send_massage(display_channel, &item->pipe_item);
}

#define MAX_SEND_VEC 100

static inline BufDescriptor *find_buf(RedChannel *channel, int buf_pos, int *buf_offset)
{
    BufDescriptor *buf;
    int pos = 0;

    for (buf = channel->send_data.bufs; buf_pos >= pos + buf->size; buf++) {
        pos += buf->size;
        ASSERT(buf != &channel->send_data.bufs[channel->send_data.n_bufs - 1]);
    }
    *buf_offset = buf_pos - pos;
    return buf;
}

static inline uint32_t __fill_iovec(RedWorker *worker, BufDescriptor *buf, int skip,
                                    struct iovec *vec, int *vec_index)
{
    uint32_t size = 0;

    switch (buf->type) {
    case BUF_TYPE_RAW:
        vec[*vec_index].iov_base = buf->data + skip;
        vec[*vec_index].iov_len = size = buf->size - skip;
        (*vec_index)++;
        break;
    case BUF_TYPE_COMPRESS_BUF: {
        RedCompressBuf *comp_buf = (RedCompressBuf *)buf->data;
        int max = buf->size - skip;
        int now;
        do {
            ASSERT(comp_buf);
            if (skip >= sizeof(comp_buf->buf)) {
                skip -= sizeof(comp_buf->buf);
                comp_buf = comp_buf->send_next;
                continue;
            }
            now = MIN(sizeof(comp_buf->buf) - skip, max);
            max -= now;
            size += now;
            vec[*vec_index].iov_base = (uint8_t*)comp_buf->buf + skip;
            vec[*vec_index].iov_len = now;
            skip = 0;
            comp_buf = comp_buf->send_next;
            (*vec_index)++;
        } while (max && *vec_index < MAX_SEND_VEC);
        break;
    }
    case BUF_TYPE_CHUNK: {
        QXLDataChunk *chunk = (QXLDataChunk *)buf->data;
        do {
            int data_size = chunk->data_size;
            int skip_now = MIN(data_size, skip);
            skip -= skip_now;
            data_size -= skip_now;

            if (data_size) {
                validate_virt(worker, (unsigned long)chunk->data, buf->slot_id, data_size,
                              buf->group_id);
                size += data_size;
                vec[*vec_index].iov_base = chunk->data + skip_now;
                vec[*vec_index].iov_len = data_size;
                (*vec_index)++;
            }
            chunk = chunk->next_chunk ?
                    (QXLDataChunk *)get_virt(worker, chunk->next_chunk, sizeof(QXLDataChunk),
                                             buf->group_id) :
                    NULL;
        } while (chunk && *vec_index < MAX_SEND_VEC);
        break;
    }
    default:
        red_error("invalid type");
    }
    return size;
}

static inline void fill_iovec(RedChannel *channel, struct iovec *vec, int *vec_size)
{
    int vec_index = 0;
    uint32_t pos = channel->send_data.pos;

    ASSERT(channel->send_data.size != pos && channel->send_data.size > pos);

    do {
        BufDescriptor *buf;
        int buf_offset;

        buf = find_buf(channel, pos, &buf_offset);
        ASSERT(buf);
        pos += __fill_iovec(channel->worker, buf, buf_offset, vec, &vec_index);
    } while (vec_index < MAX_SEND_VEC && pos != channel->send_data.size);
    *vec_size = vec_index;
}

static void inline channel_release_res(RedChannel *channel)
{
    if (!channel->send_data.item) {
        return;
    }
    channel->release_item(channel, channel->send_data.item);
    channel->send_data.item = NULL;
}

static void red_send_data(RedChannel *channel, void *item)
{
    for (;;) {
        uint32_t n = channel->send_data.size - channel->send_data.pos;
        struct iovec vec[MAX_SEND_VEC];
        int vec_size;

        if (!n) {
            channel->send_data.blocked = FALSE;
            if (channel->send_data.item) {
                channel->release_item(channel, channel->send_data.item);
                channel->send_data.item = NULL;
            }
            break;
        }
        fill_iovec(channel, vec, &vec_size);
        ASSERT(channel->peer);
        if ((n = channel->peer->cb_writev(channel->peer->ctx, vec, vec_size)) == -1) {
            switch (errno) {
            case EAGAIN:
                channel->send_data.blocked = TRUE;
                if (item) {
                    channel->hold_item(item);
                    channel->send_data.item = item;
                }
                return;
            case EINTR:
                break;
            case EPIPE:
                channel->disconnect(channel);
                return;
            default:
                red_printf("%s", strerror(errno));
                channel->disconnect(channel);
                return;
            }
        } else {
            channel->send_data.pos += n;
            stat_inc_counter(channel->out_bytes_counter, n);
        }
    }
}

static void display_channel_push_release(DisplayChannel *channel, uint8_t type, uint64_t id,
                                         uint64_t* sync_data)
{
    FreeList *free_list = &channel->send_data.free_list;
    int i;

    for (i = 0; i < MAX_CACHE_CLIENTS; i++) {
        free_list->sync[i] = MAX(free_list->sync[i], sync_data[i]);
    }

    if (free_list->res->count == free_list->res_size) {
        SpiceResorceList *new_list;
        new_list = malloc(sizeof(*new_list) + free_list->res_size * sizeof(SpiceResorceID) * 2);
        if (!new_list) {
            PANIC("malloc failed");
        }
        new_list->count = free_list->res->count;
        memcpy(new_list->resorces, free_list->res->resorces,
               new_list->count * sizeof(SpiceResorceID));
        free(free_list->res);
        free_list->res = new_list;
        free_list->res_size *= 2;
    }
    free_list->res->resorces[free_list->res->count].type = type;
    free_list->res->resorces[free_list->res->count++].id = id;
}

static inline void red_begin_send_massage(RedChannel *channel, void *item)
{
    channel->send_data.size = channel->send_data.header.size + sizeof(SpiceDataHeader);
    channel->messages_window++;
    red_send_data(channel, item);
}

static inline void display_begin_send_massage(DisplayChannel *channel, void *item)
{
    FreeList *free_list = &channel->send_data.free_list;

    if (free_list->res->count) {
        int sync_count = 0;
        int sub_index;
        int i;

        channel->base.send_data.header.sub_list = channel->base.send_data.header.size;
        for (i = 0; i < MAX_CACHE_CLIENTS; i++) {
            if (i != channel->base.id && free_list->sync[i] != 0) {
                free_list->wait.header.wait_list[sync_count].channel_type = SPICE_CHANNEL_DISPLAY;
                free_list->wait.header.wait_list[sync_count].channel_id = i;
                free_list->wait.header.wait_list[sync_count++].message_serial = free_list->sync[i];
            }
        }
        SpiceSubMessageList *sub_list = &channel->send_data.sub_list.sub_list;
        SpicedSubMessage *sub_header = channel->send_data.sub_header;
        if (sync_count) {
            sub_list->size = 2;
            add_buf((RedChannel*)channel, BUF_TYPE_RAW, sub_list,
                    sizeof(*sub_list) + 2 * sizeof(sub_list->sub_messages[0]), 0, 0);
            sub_list->sub_messages[0] = channel->base.send_data.header.size;
            sub_header[0].type = SPICE_MSG_WAIT_FOR_CHANNELS;
            sub_header[0].size = sizeof(free_list->wait.header) +
                                 sync_count * sizeof(free_list->wait.buf[0]);
            add_buf((RedChannel*)channel, BUF_TYPE_RAW, sub_header, sizeof(*sub_header), 0, 0);
            free_list->wait.header.wait_count = sync_count;
            add_buf((RedChannel*)channel, BUF_TYPE_RAW, &free_list->wait.header,
                    sub_header[0].size, 0, 0);
            sub_list->sub_messages[1] = channel->base.send_data.header.size;
            sub_index = 1;
        } else {
            sub_list->size = 1;
            add_buf((RedChannel*)channel, BUF_TYPE_RAW, sub_list,
                    sizeof(*sub_list) + sizeof(sub_list->sub_messages[0]), 0, 0);
            sub_list->sub_messages[0] = channel->base.send_data.header.size;
            sub_index = 0;
        }
        sub_header[sub_index].type = SPICE_MSG_DISPLAY_INVAL_LIST;
        sub_header[sub_index].size = sizeof(*free_list->res) + free_list->res->count *
                                     sizeof(free_list->res->resorces[0]);
        add_buf((RedChannel*)channel, BUF_TYPE_RAW, &sub_header[sub_index], sizeof(*sub_header), 0,
                0);
        add_buf((RedChannel*)channel, BUF_TYPE_RAW, free_list->res, sub_header[sub_index].size, 0,
                0);
    }
    red_begin_send_massage((RedChannel *)channel, item);
}

static inline RedChannel *red_ref_channel(RedChannel *channel)
{
    if (!channel) {
        return NULL;
    }
    ++channel->listener.refs;
    return channel;
}

static inline void red_unref_channel(RedChannel *channel)
{
    ASSERT(channel);
    if (!--channel->listener.refs) {
        free(channel);
    }
}

static inline uint8_t *red_get_image_line(RedWorker *worker, QXLDataChunk **chunk, int *offset,
                                          int stride, long phys_delta, int memslot_id,
                                          uint32_t group_id)
{
    uint8_t *ret;
    uint32_t data_size;

    validate_virt(worker, (unsigned long)*chunk, memslot_id, sizeof(QXLDataChunk),
                  group_id);
    data_size = (*chunk)->data_size;
    validate_virt(worker, (unsigned long)(*chunk)->data, memslot_id, data_size, group_id);

    if (data_size == *offset) {
        if ((*chunk)->next_chunk == 0) {
            return NULL;
        }
        *offset = 0;
        *chunk = (QXLDataChunk *)((*chunk)->next_chunk + phys_delta);
    }

    if (data_size - *offset < stride) {
        red_printf("bad chunk aligment");
        return NULL;
    }
    ret = (*chunk)->data + *offset;
    *offset += stride;
    return ret;
}

static void red_display_share_stream_buf(DisplayChannel *display_channel)
{
}

static void red_display_unshare_stream_buf(DisplayChannel *display_channel)
{
}

#define YUV32
#include "red_yuv.h"
#undef YUV32

#define YUV24
#include "red_yuv.h"
#undef YUV24

#define YUV16
#include "red_yuv.h"
#undef YUV16

static inline int red_send_stream_data(DisplayChannel *display_channel, Drawable *drawable)
{
    Stream *stream = drawable->stream;
    QXLImage *qxl_image;
    RedChannel *channel;
    RedWorker* worker;
    unsigned long data;
    int n;

    ASSERT(stream);
    ASSERT(drawable->qxl_drawable->type == QXL_DRAW_COPY);

    channel = &display_channel->base;
    worker = channel->worker;
    qxl_image = (QXLImage *)get_virt(worker,  drawable->qxl_drawable->u.copy.src_bitmap,
                                     sizeof(QXLImage), drawable->group_id);

    if (qxl_image->descriptor.type != SPICE_IMAGE_TYPE_BITMAP ||
                                            (qxl_image->bitmap.flags & QXL_BITMAP_DIRECT)) {
        return FALSE;
    }

    StreamAgent *agent = &display_channel->stream_agents[stream - worker->streams_buf];
    uint64_t time_now = red_now();
    if (time_now - agent->lats_send_time < (1000 * 1000 * 1000) / agent->fps) {
        agent->frames--;
        return TRUE;
    }

    data = qxl_image->bitmap.data;

    switch (qxl_image->bitmap.format) {
    case SPICE_BITMAP_FMT_32BIT:
        if (!red_rgb_to_yuv420_32bpp(worker, &drawable->qxl_drawable->u.copy.src_area,
                                     &qxl_image->bitmap, stream->av_frame,
                                     get_virt_delta(worker, data, drawable->group_id),
                                     get_memslot_id(worker, data),
                                     stream - worker->streams_buf, stream, drawable->group_id)) {
            return FALSE;
        }
        break;
    case SPICE_BITMAP_FMT_16BIT:
        if (!red_rgb_to_yuv420_16bpp(worker, &drawable->qxl_drawable->u.copy.src_area,
                                     &qxl_image->bitmap, stream->av_frame,
                                     get_virt_delta(worker, data, drawable->group_id),
                                     get_memslot_id(worker, data),
                                     stream - worker->streams_buf, stream, drawable->group_id)) {
            return FALSE;
        }
        break;
    case SPICE_BITMAP_FMT_24BIT:
        if (!red_rgb_to_yuv420_24bpp(worker, &drawable->qxl_drawable->u.copy.src_area,
                                     &qxl_image->bitmap, stream->av_frame,
                                     get_virt_delta(worker, data, drawable->group_id),
                                     get_memslot_id(worker, data),
                                     stream - worker->streams_buf, stream, drawable->group_id)) {
            return FALSE;
        }
        break;
    default:
        red_printf_some(1000, "unsupported format %d", qxl_image->bitmap.format);
        return FALSE;
    }
#if 1
    uint32_t min_buf_size = stream->av_ctx->width * stream->av_ctx->height * sizeof(uint32_t) / 2;
    min_buf_size += FF_MIN_BUFFER_SIZE;
    if (display_channel->send_data.stream_outbuf_size < min_buf_size) {
        uint8_t *new_buf;

        if (!(new_buf = malloc(min_buf_size + FF_INPUT_BUFFER_PADDING_SIZE))) {
            return FALSE;
        }

        red_display_unshare_stream_buf(display_channel);
        free(display_channel->send_data.stream_outbuf);
        display_channel->send_data.stream_outbuf = new_buf;
        display_channel->send_data.stream_outbuf_size = min_buf_size;
        red_display_share_stream_buf(display_channel);
    }
    n = avcodec_encode_video(stream->av_ctx, display_channel->send_data.stream_outbuf,
                             display_channel->send_data.stream_outbuf_size,
                             stream->av_frame);

    if (n <= 0) {
        red_printf("avcodec_encode_video failed");
        return FALSE;
    }

    if (n > display_channel->send_data.stream_outbuf_size) {
        PANIC("buf error");
    }
#else
    for (;;) {
        n = avcodec_encode_video(stream->av_ctx, display_channel->send_data.stream_outbuf,
                                 display_channel->send_data.stream_outbuf_size,
                                 stream->av_frame);
        if (n < 0) {
            uint8_t *new_buf;
            size_t max_size;
            size_t new_size;

            max_size = stream->av_ctx->width * stream->av_ctx->height * sizeof(uint32_t);
            max_size += MAX(1024, max_size / 10);

            if (display_channel->send_data.stream_outbuf_size == max_size) {
                return FALSE;
            }

            new_size = display_channel->send_data.stream_outbuf_size * 2;
            new_size = MIN(new_size, max_size);

            if (!(new_buf = malloc(new_size + FF_INPUT_BUFFER_PADDING_SIZE))) {
                return FALSE;
            }
            red_printf("new streaming video buf size %u", new_size);
            red_display_unshare_stream_buf(display_channel);
            free(display_channel->send_data.stream_outbuf);
            display_channel->send_data.stream_outbuf = new_buf;
            display_channel->send_data.stream_outbuf_size = new_size;
            red_display_share_stream_buf(display_channel);
            continue;
        }
        ASSERT(n <= display_channel->send_data.stream_outbuf_size);
        break;
    }
 #endif
    channel->send_data.header.type = SPICE_MSG_DISPLAY_STREAM_DATA;
    SpiceMsgDisplayStreamData* stream_data = &display_channel->send_data.u.stream_data;
    add_buf(channel, BUF_TYPE_RAW, stream_data, sizeof(SpiceMsgDisplayStreamData), 0, 0);
    add_buf(channel, BUF_TYPE_RAW, display_channel->send_data.stream_outbuf,
            n + FF_INPUT_BUFFER_PADDING_SIZE, 0, 0);

    stream_data->id = stream - worker->streams_buf;
    stream_data->multi_media_time = drawable->qxl_drawable->mm_time;
    stream_data->data_size = n;
    stream_data->ped_size = FF_INPUT_BUFFER_PADDING_SIZE;
    display_begin_send_massage(display_channel, NULL);
    agent->lats_send_time = time_now;
    return TRUE;
}

static inline void send_qxl_drawable(DisplayChannel *display_channel, Drawable *item)
{
    RedChannel *channel;

    ASSERT(display_channel);
    channel = &display_channel->base;

    if (item->stream && red_send_stream_data(display_channel, item)) {
        return;
    }
    red_send_qxl_drawable(display_channel->base.worker, display_channel, item);
}

static void red_send_mode(DisplayChannel *display_channel)
{
    RedChannel *channel;
    RedWorker *worker;

    ASSERT(display_channel);
    worker = display_channel->base.worker;

    if (!worker->surface.context.canvas) {
        return;
    }

    channel = &display_channel->base;
    channel->send_data.header.type = SPICE_MSG_DISPLAY_MODE;
    display_channel->send_data.u.mode.x_res = worker->surface.context.width;
    display_channel->send_data.u.mode.y_res = worker->surface.context.height;
    display_channel->send_data.u.mode.bits = worker->surface.context.depth;

    add_buf(channel, BUF_TYPE_RAW, &display_channel->send_data.u.mode, sizeof(SpiceMsgDisplayMode), 0, 0);

    display_begin_send_massage(display_channel, NULL);
}

static void red_send_set_ack(RedChannel *channel)
{
    ASSERT(channel);
    channel->send_data.header.type = SPICE_MSG_SET_ACK;
    channel->send_data.u.ack.generation = ++channel->ack_generation;
    channel->send_data.u.ack.window = channel->client_ack_window;
    channel->messages_window = 0;

    add_buf(channel, BUF_TYPE_RAW, &channel->send_data.u.ack, sizeof(SpiceMsgSetAck), 0, 0);
    red_begin_send_massage(channel, NULL);
}

static inline void red_send_verb(RedChannel *channel, uint16_t verb)
{
    ASSERT(channel);
    channel->send_data.header.type = verb;
    red_begin_send_massage(channel, NULL);
}

static inline void display_send_verb(DisplayChannel *channel, uint16_t verb)
{
    ASSERT(channel);
    channel->base.send_data.header.type = verb;
    display_begin_send_massage(channel, NULL);
}

static inline void __red_send_inval(RedChannel *channel, CacheItem *cach_item,
                                    SpiceMsgDisplayInvalOne *inval_one)
{
    channel->send_data.header.type = cach_item->inval_type;
    inval_one->id = *(uint64_t *)&cach_item->id;
    add_buf(channel, BUF_TYPE_RAW, inval_one, sizeof(*inval_one), 0, 0);
}

static void red_send_inval(RedChannel *channel, CacheItem *cach_item, SpiceMsgDisplayInvalOne *inval_one)
{
    __red_send_inval(channel, cach_item, inval_one);
    red_begin_send_massage(channel, NULL);
}

static void red_display_send_inval(DisplayChannel *display_channel, CacheItem *cach_item)
{
    __red_send_inval((RedChannel *)display_channel, cach_item,
                     &display_channel->send_data.u.inval_one);
    display_begin_send_massage(display_channel, NULL);
}

static void display_channel_send_migrate(DisplayChannel *display_channel)
{
    display_channel->base.send_data.header.type = SPICE_MSG_MIGRATE;
    display_channel->send_data.u.migrate.flags = SPICE_MIGRATE_NEED_FLUSH |
                                                 SPICE_MIGRATE_NEED_DATA_TRANSFER;
    add_buf((RedChannel*)display_channel, BUF_TYPE_RAW, &display_channel->send_data.u.migrate,
            sizeof(display_channel->send_data.u.migrate), 0, 0);
    display_channel->expect_migrate_mark = TRUE;
    display_begin_send_massage(display_channel, NULL);
}

static void display_channel_send_migrate_data(DisplayChannel *display_channel)
{
    DisplayChannelMigrateData* display_data;

    display_channel->base.send_data.header.type = SPICE_MSG_MIGRATE_DATA;
    ASSERT(display_channel->pixmap_cache);
    display_data = &display_channel->send_data.u.migrate_data;
    display_data->magic = DISPLAY_MIGRATE_DATA_MAGIC;
    ASSERT(MAX_CACHE_CLIENTS == 4); //MIGRATE_DATA_VERSION dependent
    display_data->version = DISPLAY_MIGRATE_DATA_VERSION;

    display_data->message_serial = channel_message_serial((RedChannel *)display_channel);

    display_data->pixmap_cache_freezer = pixmap_cache_freeze(display_channel->pixmap_cache);
    display_data->pixmap_cache_id = display_channel->pixmap_cache->id;
    display_data->pixmap_cache_size = display_channel->pixmap_cache->size;
    memcpy(display_data->pixmap_cache_clients, display_channel->pixmap_cache->sync,
           sizeof(display_data->pixmap_cache_clients));

    ASSERT(display_channel->glz_dict);
    red_freeze_glz(display_channel);
    display_data->glz_dict_id = display_channel->glz_dict->id;
    glz_enc_dictionary_get_restore_data(display_channel->glz_dict->dict,
                                        &display_data->glz_dict_restore_data,
                                        &display_channel->glz_data.usr);

    add_buf((RedChannel *)display_channel, BUF_TYPE_RAW, &display_channel->send_data.u.migrate_data,
            sizeof(display_channel->send_data.u.migrate_data), 0, 0);
    display_begin_send_massage(display_channel, NULL);
}

static void display_channel_pixmap_sync(DisplayChannel *display_channel)
{
    SpiceMsgWaitForChannels *wait;
    PixmapCache *pixmap_cache;


    display_channel->base.send_data.header.type = SPICE_MSG_WAIT_FOR_CHANNELS;
    wait = &display_channel->send_data.u.wait.header;
    pixmap_cache = display_channel->pixmap_cache;


    pthread_mutex_lock(&pixmap_cache->lock);

    wait->wait_count = 1;
    wait->wait_list[0].channel_type = SPICE_CHANNEL_DISPLAY;
    wait->wait_list[0].channel_id = pixmap_cache->generation_initiator.client;
    wait->wait_list[0].message_serial = pixmap_cache->generation_initiator.message;
    display_channel->pixmap_cache_generation = pixmap_cache->generation;
    display_channel->pending_pixmaps_sync = FALSE;

    pthread_mutex_unlock(&pixmap_cache->lock);

    add_buf((RedChannel *)display_channel, BUF_TYPE_RAW, wait,
            sizeof(*wait) + sizeof(wait->wait_list[0]), 0, 0);
    display_begin_send_massage(display_channel, NULL);
}

static void display_channel_reset_cache(DisplayChannel *display_channel)
{
    SpiceMsgWaitForChannels *wait = &display_channel->send_data.u.wait.header;

    display_channel->base.send_data.header.type = SPICE_MSG_DISPLAY_INVAL_ALL_PIXMAPS;
    pixmap_cache_reset(display_channel->pixmap_cache, display_channel, wait);

    add_buf((RedChannel *)display_channel, BUF_TYPE_RAW, wait,
            sizeof(*wait) + wait->wait_count * sizeof(wait->wait_list[0]), 0, 0);
    display_begin_send_massage(display_channel, NULL);
}

static void red_send_image(DisplayChannel *display_channel, ImageItem *item)
{
    RedChannel *channel;
    RedImage *red_image;
    RedWorker *worker;
    SpiceBitmap bitmap;

    ASSERT(display_channel && item);
    channel = &display_channel->base;
    worker = channel->worker;

    red_image = alloc_image(display_channel);
    ASSERT(red_image);

    QXL_SET_IMAGE_ID(red_image, QXL_IMAGE_GROUP_RED, ++worker->bits_unique);
    red_image->descriptor.type = SPICE_IMAGE_TYPE_BITMAP;
    red_image->descriptor.flags = 0;
    red_image->descriptor.width = item->width;
    red_image->descriptor.height = item->height;

    bitmap.format = SPICE_BITMAP_FMT_32BIT;
    bitmap.flags = QXL_BITMAP_DIRECT;
    bitmap.flags |= item->top_down ? QXL_BITMAP_TOP_DOWN : 0;
    bitmap.x = item->width;
    bitmap.y = item->height;
    bitmap.stride = item->stride;
    bitmap.palette = 0;
    bitmap.data = (SPICE_ADDRESS)item->data;

    channel->send_data.header.type = SPICE_MSG_DISPLAY_DRAW_COPY;

    add_buf(channel, BUF_TYPE_RAW, &display_channel->send_data.u.copy, sizeof(SpiceMsgDisplayDrawCopy), 0, 0);
    display_channel->send_data.u.copy.base.box.left = item->pos.x;
    display_channel->send_data.u.copy.base.box.top = item->pos.y;
    display_channel->send_data.u.copy.base.box.right = item->pos.x + bitmap.x;
    display_channel->send_data.u.copy.base.box.bottom = item->pos.y + bitmap.y;
    display_channel->send_data.u.copy.base.clip.type = SPICE_CLIP_TYPE_NONE;
    display_channel->send_data.u.copy.base.clip.data = 0;
    display_channel->send_data.u.copy.data.rop_decriptor = SPICE_ROPD_OP_PUT;
    display_channel->send_data.u.copy.data.src_area.left = 0;
    display_channel->send_data.u.copy.data.src_area.top = 0;
    display_channel->send_data.u.copy.data.src_area.right = bitmap.x;
    display_channel->send_data.u.copy.data.src_area.bottom = bitmap.y;
    display_channel->send_data.u.copy.data.scale_mode = 0;
    display_channel->send_data.u.copy.data.src_bitmap = channel->send_data.header.size;
    display_channel->send_data.u.copy.data.mask.bitmap = 0;

    compress_send_data_t comp_send_data;

    if (red_quic_compress_image(display_channel, red_image, &bitmap, &comp_send_data,
                                worker->internal_groupslot_id)) {
        add_buf(channel, BUF_TYPE_RAW, red_image, comp_send_data.raw_size, 0, 0);
        add_buf(channel, BUF_TYPE_COMPRESS_BUF, comp_send_data.comp_buf,
                comp_send_data.comp_buf_size, 0, 0);
    } else {
        red_image->descriptor.type = SPICE_IMAGE_TYPE_BITMAP;
        red_image->bitmap = bitmap;
        red_image->bitmap.flags &= ~QXL_BITMAP_DIRECT;
        add_buf(channel, BUF_TYPE_RAW, red_image, sizeof(SpiceBitmapImage), 0, 0);
        red_image->bitmap.data = channel->send_data.header.size;
        add_buf(channel, BUF_TYPE_RAW, item->data, bitmap.y * bitmap.stride, 0, 0);
    }
    display_begin_send_massage(display_channel, &item->link);
}

static void red_display_send_upgrade(DisplayChannel *display_channel, UpgradeItem *item)
{
    RedChannel *channel;
    QXLDrawable *qxl_drawable;
    SpiceMsgDisplayDrawCopy *copy = &display_channel->send_data.u.copy;

    ASSERT(display_channel && item && item->drawable);
    channel = &display_channel->base;

    channel->send_data.header.type = SPICE_MSG_DISPLAY_DRAW_COPY;

    qxl_drawable = item->drawable->qxl_drawable;
    ASSERT(qxl_drawable->type == QXL_DRAW_COPY);
    ASSERT(qxl_drawable->u.copy.rop_decriptor == SPICE_ROPD_OP_PUT);
    ASSERT(qxl_drawable->u.copy.mask.bitmap == 0);

    add_buf(channel, BUF_TYPE_RAW, copy, sizeof(SpiceMsgDisplayDrawCopy), 0, 0);
    copy->base.box = qxl_drawable->bbox;
    copy->base.clip.type = SPICE_CLIP_TYPE_RECTS;
    copy->base.clip.data = channel->send_data.header.size;
    add_buf(channel, BUF_TYPE_RAW, &item->region.num_rects, sizeof(uint32_t), 0, 0);
    add_buf(channel, BUF_TYPE_RAW, item->region.rects, sizeof(SpiceRect) * item->region.num_rects, 0, 0);
    copy->data = qxl_drawable->u.copy;
    fill_bits(display_channel, &copy->data.src_bitmap, item->drawable);

    display_begin_send_massage(display_channel, &item->base);
}

static void red_display_send_stream_start(DisplayChannel *display_channel, StreamAgent *agent)
{
    RedChannel *channel = &display_channel->base;
    Stream *stream = agent->stream;

    agent->lats_send_time = 0;
    ASSERT(stream);
    channel->send_data.header.type = SPICE_MSG_DISPLAY_STREAM_CREATE;
    SpiceMsgDisplayStreamCreate *stream_create = &display_channel->send_data.u.stream_create.message;
    stream_create->id = agent - display_channel->stream_agents;
    stream_create->flags = stream->top_down ? SPICE_STREAM_FLAGS_TOP_DOWN : 0;
    stream_create->codec_type = SPICE_VIDEO_CODEC_TYPE_MJPEG;

    stream_create->src_width = stream->width;
    stream_create->src_height = stream->height;
    stream_create->stream_width = ALIGN(stream_create->src_width, 2);
    stream_create->stream_height = ALIGN(stream_create->src_height, 2);
    stream_create->dest = stream->dest_area;

    add_buf(channel, BUF_TYPE_RAW, stream_create, sizeof(*stream_create), 0, 0);
    if (stream->current) {
        QXLDrawable *qxl_drawable = stream->current->qxl_drawable;
        stream_create->clip = qxl_drawable->clip;
        if (qxl_drawable->clip.type == SPICE_CLIP_TYPE_RECTS) {
            fill_rects_clip(channel, &stream_create->clip.data, stream->current->group_id);
        } else {
            ASSERT(qxl_drawable->clip.type == SPICE_CLIP_TYPE_NONE);
        }
        display_begin_send_massage(display_channel, &stream->current->pipe_item);
    } else {
        stream_create->clip.type = SPICE_CLIP_TYPE_RECTS;
        stream_create->clip.data = channel->send_data.header.size;
        display_channel->send_data.u.stream_create.num_rects = 0;
        add_buf(channel, BUF_TYPE_RAW, &display_channel->send_data.u.stream_create.num_rects,
                sizeof(uint32_t), 0, 0);
        display_begin_send_massage(display_channel, NULL);
    }
}

static void red_display_send_stream_clip(DisplayChannel *display_channel,
                                         StreamClipItem *item)
{
    RedChannel *channel = &display_channel->base;

    StreamAgent *agent = item->stream_agent;
    Stream *stream = agent->stream;

    ASSERT(stream);

    channel->send_data.header.type = SPICE_MSG_DISPLAY_STREAM_CLIP;
    SpiceMsgDisplayStreamClip *stream_clip = &display_channel->send_data.u.stream_clip;
    add_buf(channel, BUF_TYPE_RAW, stream_clip, sizeof(*stream_clip), 0, 0);
    stream_clip->id = agent - display_channel->stream_agents;
    if ((stream_clip->clip.type = item->clip_type) == SPICE_CLIP_TYPE_NONE) {
        stream_clip->clip.data = 0;
    } else {
        ASSERT(stream_clip->clip.type == SPICE_CLIP_TYPE_RECTS);
        stream_clip->clip.data = channel->send_data.header.size;
        add_buf(channel, BUF_TYPE_RAW, &item->region.num_rects, sizeof(uint32_t), 0, 0);
        add_buf(channel, BUF_TYPE_RAW, item->region.rects,
                item->region.num_rects * sizeof(SpiceRect), 0, 0);
    }
    display_begin_send_massage(display_channel, item);
}

static void red_display_send_stream_end(DisplayChannel *display_channel, StreamAgent* agent)
{
    RedChannel *channel = &display_channel->base;
    channel->send_data.header.type = SPICE_MSG_DISPLAY_STREAM_DESTROY;
    display_channel->send_data.u.stream_destroy.id = agent - display_channel->stream_agents;
    add_buf(channel, BUF_TYPE_RAW, &display_channel->send_data.u.stream_destroy,
            sizeof(SpiceMsgDisplayStreamDestroy), 0, 0);
    display_begin_send_massage(display_channel, NULL);
}

static void red_cursor_send_inval(CursorChannel *channel, CacheItem *cach_item)
{
    ASSERT(channel);
    red_send_inval((RedChannel *)channel, cach_item, &channel->send_data.u.inval_one);
}

static void red_send_cursor_init(CursorChannel *channel)
{
    RedWorker *worker;
    ASSERT(channel);

    worker = channel->base.worker;

    channel->base.send_data.header.type = SPICE_MSG_CURSOR_INIT;
    channel->send_data.u.cursor_init.visible = worker->cursor_visible;
    channel->send_data.u.cursor_init.position = worker->cursor_position;
    channel->send_data.u.cursor_init.trail_length = worker->cursor_trail_length;
    channel->send_data.u.cursor_init.trail_frequency = worker->cursor_trail_frequency;
    add_buf(&channel->base, BUF_TYPE_RAW, &channel->send_data.u.cursor_init, sizeof(SpiceMsgCursorInit),
            0, 0);

    fill_cursor(channel, &channel->send_data.u.cursor_init.cursor, worker->cursor);

    red_begin_send_massage(&channel->base, worker->cursor);
}

static void red_send_local_cursor(CursorChannel *cursor_channel, LocalCursor *cursor)
{
    RedChannel *channel;

    ASSERT(cursor_channel);

    channel = &cursor_channel->base;
    channel->send_data.header.type = SPICE_MSG_CURSOR_SET;
    cursor_channel->send_data.u.cursor_set.postition = cursor->position;
    cursor_channel->send_data.u.cursor_set.visible = channel->worker->cursor_visible;
    add_buf(channel, BUF_TYPE_RAW, &cursor_channel->send_data.u.cursor_set,
            sizeof(SpiceMsgCursorSet), 0, 0);
    fill_cursor(cursor_channel, &cursor_channel->send_data.u.cursor_set.cursor, &cursor->base);

    red_begin_send_massage(channel, cursor);

    red_release_cursor(channel->worker, (CursorItem *)cursor);
}

static void cursor_channel_send_migrate(CursorChannel *cursor_channel)
{
    cursor_channel->base.send_data.header.type = SPICE_MSG_MIGRATE;
    cursor_channel->send_data.u.migrate.flags = 0;
    add_buf((RedChannel*)cursor_channel, BUF_TYPE_RAW, &cursor_channel->send_data.u.migrate,
            sizeof(cursor_channel->send_data.u.migrate), 0, 0);
    red_begin_send_massage((RedChannel*)cursor_channel, NULL);
}

static void red_send_cursor(CursorChannel *cursor_channel, CursorItem *cursor)
{
    RedChannel *channel;
    QXLCursorCmd *cmd;

    ASSERT(cursor_channel);

    channel = &cursor_channel->base;

    cmd = cursor->qxl_cursor;
    switch (cmd->type) {
    case QXL_CURSOR_MOVE:
        channel->send_data.header.type = SPICE_MSG_CURSOR_MOVE;
        cursor_channel->send_data.u.cursor_move.postition = cmd->u.position;
        add_buf(channel, BUF_TYPE_RAW, &cursor_channel->send_data.u.cursor_move,
                sizeof(SpiceMsgCursorMove), 0, 0);
        break;
    case QXL_CURSOR_SET:
        channel->send_data.header.type = SPICE_MSG_CURSOR_SET;
        cursor_channel->send_data.u.cursor_set.postition = cmd->u.set.position;
        cursor_channel->send_data.u.cursor_set.visible = channel->worker->cursor_visible;
        add_buf(channel, BUF_TYPE_RAW, &cursor_channel->send_data.u.cursor_set,
                sizeof(SpiceMsgCursorSet), 0, 0);
        fill_cursor(cursor_channel, &cursor_channel->send_data.u.cursor_set.cursor, cursor);
        break;
    case QXL_CURSOR_HIDE:
        channel->send_data.header.type = SPICE_MSG_CURSOR_HIDE;
        break;
    case QXL_CURSOR_TRAIL:
        channel->send_data.header.type = SPICE_MSG_CURSOR_TRAIL;
        cursor_channel->send_data.u.cursor_trail.length = cmd->u.trail.length;
        cursor_channel->send_data.u.cursor_trail.frequency = cmd->u.trail.frequency;
        add_buf(channel, BUF_TYPE_RAW, &cursor_channel->send_data.u.cursor_trail,
                sizeof(SpiceMsgCursorTrail), 0, 0);
        break;
    default:
        red_error("bad cursor command %d", cmd->type);
    }

    red_begin_send_massage(channel, cursor);

    red_release_cursor(channel->worker, cursor);
}

static inline PipeItem *red_pipe_get(RedChannel *channel)
{
    PipeItem *item;
    if (!channel || channel->send_data.blocked ||
                                            !(item = (PipeItem *)ring_get_tail(&channel->pipe))) {
        return NULL;
    }

    if (channel->messages_window > channel->client_ack_window * 2) {
        channel->send_data.blocked = TRUE;
        return NULL;
    }

    --channel->pipe_size;
    ring_remove(&item->link);
    return item;
}

static void display_channel_push(RedWorker *worker)
{
    PipeItem *pipe_item;

    while ((pipe_item = red_pipe_get((RedChannel *)worker->display_channel))) {
        DisplayChannel *display_channel;
        display_channel = (DisplayChannel *)red_ref_channel((RedChannel *)worker->display_channel);
        red_display_reset_send_data(display_channel);
        switch (pipe_item->type) {
        case PIPE_ITEM_TYPE_DRAW: {
            Drawable *drawable = CONTAINEROF(pipe_item, Drawable, pipe_item);
            send_qxl_drawable(display_channel, drawable);
            release_drawable(worker, drawable);
            break;
        }
        case PIPE_ITEM_TYPE_INVAL_ONE:
            red_display_send_inval(display_channel, (CacheItem *)pipe_item);
            free(pipe_item);
            break;
        case PIPE_ITEM_TYPE_STREAM_CREATE: {
            StreamAgent *agent = CONTAINEROF(pipe_item, StreamAgent, create_item);
            red_display_send_stream_start(display_channel, agent);
            red_display_release_stream(display_channel, agent);
            break;
        }
        case PIPE_ITEM_TYPE_STREAM_CLIP: {
            StreamClipItem* clip_item = (StreamClipItem *)pipe_item;
            red_display_send_stream_clip(display_channel, clip_item);
            red_display_release_stream_clip(display_channel, clip_item);
            break;
        }
        case PIPE_ITEM_TYPE_STREAM_DESTROY: {
            StreamAgent *agent = CONTAINEROF(pipe_item, StreamAgent, destroy_item);
            red_display_send_stream_end(display_channel, agent);
            red_display_release_stream(display_channel, agent);
            break;
        }
        case PIPE_ITEM_TYPE_UPGRADE:
            red_display_send_upgrade(display_channel, (UpgradeItem *)pipe_item);
            release_upgrade_item(worker, (UpgradeItem *)pipe_item);
            break;
        case PIPE_ITEM_TYPE_VERB:
            display_send_verb(display_channel, ((VerbItem*)pipe_item)->verb);
            free(pipe_item);
            break;
        case PIPE_ITEM_TYPE_MODE:
            red_send_mode(display_channel);
            free(pipe_item);
            break;
        case PIPE_ITEM_TYPE_MIGRATE:
            red_printf("PIPE_ITEM_TYPE_MIGRATE");
            display_channel_send_migrate(display_channel);
            free(pipe_item);
            break;
        case PIPE_ITEM_TYPE_MIGRATE_DATA:
            display_channel_send_migrate_data(display_channel);
            free(pipe_item);
            break;
        case PIPE_ITEM_TYPE_SET_ACK:
            red_send_set_ack((RedChannel *)display_channel);
            free(pipe_item);
            break;
        case PIPE_ITEM_TYPE_IMAGE:
            red_send_image(display_channel, (ImageItem *)pipe_item);
            release_image_item((ImageItem *)pipe_item);
            break;
        case PIPE_ITEM_TYPE_PIXMAP_SYNC:
            display_channel_pixmap_sync(display_channel);
            free(pipe_item);
            break;
        case PIPE_ITEM_TYPE_PIXMAP_RESET:
            display_channel_reset_cache(display_channel);
            free(pipe_item);
            break;
        case PIPE_ITEM_TYPE_INVAL_PALLET_CACHE:
            red_reset_palette_cache(display_channel);
            red_send_verb((RedChannel *)display_channel, SPICE_MSG_DISPLAY_INVAL_ALL_PALETTES);
            free(pipe_item);
            break;
        default:
            red_error("invalid pipe item type");
        }
        red_unref_channel((RedChannel *)display_channel);
    }
}

static void cursor_channel_push(RedWorker *worker)
{
    PipeItem *pipe_item;

    while ((pipe_item = red_pipe_get((RedChannel *)worker->cursor_channel))) {
        CursorChannel *cursor_channel;

        cursor_channel = (CursorChannel *)red_ref_channel((RedChannel *)worker->cursor_channel);
        red_channel_reset_send_data((RedChannel*)cursor_channel);
        switch (pipe_item->type) {
        case PIPE_ITEM_TYPE_CURSOR:
            red_send_cursor(cursor_channel, (CursorItem *)pipe_item);
            break;
        case PIPE_ITEM_TYPE_LOCAL_CURSOR:
            red_send_local_cursor(cursor_channel, (LocalCursor *)pipe_item);
            break;
        case PIPE_ITEM_TYPE_INVAL_ONE:
            red_cursor_send_inval(cursor_channel, (CacheItem *)pipe_item);
            free(pipe_item);
            break;
        case PIPE_ITEM_TYPE_VERB:
            red_send_verb((RedChannel *)cursor_channel, ((VerbItem*)pipe_item)->verb);
            free(pipe_item);
            break;
        case PIPE_ITEM_TYPE_MIGRATE:
            red_printf("PIPE_ITEM_TYPE_MIGRATE");
            cursor_channel_send_migrate(cursor_channel);
            free(pipe_item);
            break;
        case PIPE_ITEM_TYPE_SET_ACK:
            red_send_set_ack((RedChannel *)cursor_channel);
            free(pipe_item);
            break;
        case PIPE_ITEM_TYPE_CURSOR_INIT:
            red_send_cursor_init(cursor_channel);
            free(pipe_item);
            break;
        case PIPE_ITEM_TYPE_INVAL_CURSOR_CACHE:
            red_reset_cursor_cache(cursor_channel);
            red_send_verb((RedChannel *)cursor_channel, SPICE_MSG_CURSOR_INVAL_ALL);
            free(pipe_item);
            break;
        default:
            red_error("invalid pipe item type");
        }
        red_unref_channel((RedChannel *)cursor_channel);
    }
}

static inline void red_push(RedWorker *worker)
{
    cursor_channel_push(worker);
    display_channel_push(worker);
}

typedef struct ShowTreeData {
    RedWorker *worker;
    int level;
    Container *container;
} ShowTreeData;

static void __show_tree_call(TreeItem *item, void *data)
{
    ShowTreeData *tree_data = data;
    const char *item_prefix = "|--";
    int i;

    while (tree_data->container != item->container) {
        ASSERT(tree_data->container);
        tree_data->level--;
        tree_data->container = tree_data->container->base.container;
    }

    switch (item->type) {
    case TREE_ITEM_TYPE_DRAWABLE: {
        Drawable *drawable = CONTAINEROF(item, Drawable, tree_item);
        const int max_indent = 200;
        char indent_str[max_indent + 1];
        int indent_str_len;

        for (i = 0; i < tree_data->level; i++) {
            printf("  ");
        }
        printf(item_prefix, 0);
        show_qxl_drawable(tree_data->worker, drawable->qxl_drawable, NULL);
        for (i = 0; i < tree_data->level; i++) {
            printf("  ");
        }
        printf("|  ");
        show_draw_item(tree_data->worker, &drawable->tree_item, NULL);
        indent_str_len = MIN(max_indent, strlen(item_prefix) + tree_data->level * 2);
        memset(indent_str, ' ', indent_str_len);
        indent_str[indent_str_len] = 0;
        region_dump(&item->rgn, indent_str);
        printf("\n");
        break;
    }
    case TREE_ITEM_TYPE_CONTAINER:
        tree_data->level++;
        tree_data->container = (Container *)item;
        break;
    case TREE_ITEM_TYPE_SHADOW:
        break;
    }
}

void red_show_tree(RedWorker *worker)
{
    ShowTreeData show_tree_data;
    show_tree_data.worker = worker;
    show_tree_data.level = 0;
    show_tree_data.container = NULL;
    current_tree_for_each(worker, __show_tree_call, &show_tree_data);
}

static inline int channel_is_connected(RedChannel *channel)
{
    return !!channel->peer;
}

static void red_disconnect_channel(RedChannel *channel)
{
    channel_release_res(channel);
    red_pipe_clear(channel);

    channel->peer->cb_free(channel->peer);

    channel->peer = NULL;
    channel->send_data.blocked = FALSE;
    channel->send_data.size = channel->send_data.pos = 0;
    red_unref_channel(channel);
}

static void red_disconnect_display(RedChannel *channel)
{
    DisplayChannel *display_channel;

    if (!channel || !channel->peer) {
        return;
    }

    display_channel = (DisplayChannel *)channel;
    ASSERT(display_channel == channel->worker->display_channel);
#ifdef COMPRESS_STAT
    print_compress_stats(display_channel);
#endif
    channel->worker->display_channel = NULL;
    red_display_unshare_stream_buf(display_channel);
    red_release_pixmap_cache(display_channel);
    red_release_glz(display_channel);
    red_reset_palette_cache(display_channel);
    free(display_channel->send_data.stream_outbuf);
    red_display_reset_compress_buf(display_channel);
    while (display_channel->send_data.free_compress_bufs) {
        RedCompressBuf *buf = display_channel->send_data.free_compress_bufs;
        display_channel->send_data.free_compress_bufs = buf->next;
        free(buf);
    }
    free(display_channel->send_data.free_list.res);
    red_display_destroy_streams(display_channel);
    red_disconnect_channel(channel);
}

static void red_migrate_display(RedWorker *worker)
{
    if (worker->display_channel) {
        red_pipe_add_verb(&worker->display_channel->base, SPICE_MSG_DISPLAY_STREAM_DESTROY_ALL);
        red_pipe_add_type(&worker->display_channel->base, PIPE_ITEM_TYPE_MIGRATE);
    }
}

static void destroy_cairo_canvas(CairoCanvas *canvas)
{
    cairo_t *cairo;

    if (!canvas) {
        return;
    }

    cairo = canvas_get_cairo(canvas);
    canvas_destroy(canvas);
    cairo_destroy(cairo);
}

static void validate_area_nop(void *canvas, int32_t stride, uint8_t *line_0, const SpiceRect *area)
{
}

static void init_cairo_draw_funcs(RedWorker *worker)
{
    worker->draw_funcs.draw_fill = (draw_fill_t)canvas_draw_fill;
    worker->draw_funcs.draw_copy = (draw_copy_t)canvas_draw_copy;
    worker->draw_funcs.draw_opaque = (draw_opaque_t)canvas_draw_opaque;
    worker->draw_funcs.copy_bits = (copy_bits_t)canvas_copy_bits;
    worker->draw_funcs.draw_text = (draw_text_t)canvas_draw_text;
    worker->draw_funcs.draw_stroke = (draw_stroke_t)canvas_draw_stroke;
    worker->draw_funcs.draw_rop3 = (draw_rop3_t)canvas_draw_rop3;
    worker->draw_funcs.draw_blend = (draw_blend_t)canvas_draw_blend;
    worker->draw_funcs.draw_blackness = (draw_blackness_t)canvas_draw_blackness;
    worker->draw_funcs.draw_whiteness = (draw_whiteness_t)canvas_draw_whiteness;
    worker->draw_funcs.draw_invers = (draw_invers_t)canvas_draw_invers;
    worker->draw_funcs.draw_transparent = (draw_transparent_t)canvas_draw_transparent;
    worker->draw_funcs.draw_alpha_blend = (draw_alpha_blend_t)canvas_draw_alpha_blend;
    worker->draw_funcs.read_pixels = (read_pixels_t)canvas_read_bits;

    worker->draw_funcs.set_top_mask = (set_top_mask_t)canvas_group_start;
    worker->draw_funcs.clear_top_mask = (clear_top_mask_t)canvas_group_end;
    worker->draw_funcs.validate_area = validate_area_nop;
    worker->draw_funcs.destroy = (destroy_t)destroy_cairo_canvas;
}

static CairoCanvas *create_cairo_context(RedWorker *worker, uint32_t width, uint32_t height,
                                         int32_t stride, uint8_t depth, void *line_0)
{
    cairo_surface_t *cairo_surface;
    cairo_t *cairo;

    cairo_surface = cairo_image_surface_create_for_data(line_0,  CAIRO_FORMAT_RGB24, width, height,
                                                        stride);
    if (cairo_surface_status(cairo_surface) != CAIRO_STATUS_SUCCESS) {
        red_error("create cairo surface failed, %s",
                  cairo_status_to_string(cairo_surface_status(cairo_surface)));
    }
    cairo = cairo_create(cairo_surface);
    cairo_surface_destroy(cairo_surface);
    if (cairo_status(cairo) != CAIRO_STATUS_SUCCESS) {
        red_error("create cairo failed, %s",
                  cairo_status_to_string(cairo_status(cairo)));
    }

    return canvas_create(cairo, depth, &worker->image_cache, image_cache_put, image_cache_get,
                         worker, cb_get_virt_preload_group, worker,
                         cb_validate_virt_preload_group);
}

static void destroy_gl_canvas(GLCanvas *canvas)
{
    OGLCtx *ctx;

    if (!canvas) {
        return;
    }

    ctx = gl_canvas_get_usr_data(canvas);
    ASSERT(ctx);
    gl_canvas_destroy(canvas, 0);
    oglctx_destroy(ctx);
}

static void gl_validate_area(GLCanvas *canvas, int32_t stride, uint8_t *line_0, const SpiceRect *area)
{
    int h;

    if (!(h = area->bottom - area->top)) {
        return;
    }

    ASSERT(stride < 0);
    uint8_t *dest = line_0 + (area->top * stride) + area->left * sizeof(uint32_t);
    dest += (h - 1) * stride;
    gl_canvas_read_pixels(canvas, dest, -stride, area);
}

static void init_ogl_draw_funcs(RedWorker *worker)
{
    worker->draw_funcs.draw_fill = (draw_fill_t)gl_canvas_draw_fill;
    worker->draw_funcs.draw_copy = (draw_copy_t)gl_canvas_draw_copy;
    worker->draw_funcs.draw_opaque = (draw_opaque_t)gl_canvas_draw_opaque;
    worker->draw_funcs.copy_bits = (copy_bits_t)gl_canvas_copy_pixels;
    worker->draw_funcs.draw_text = (draw_text_t)gl_canvas_draw_text;
    worker->draw_funcs.draw_stroke = (draw_stroke_t)gl_canvas_draw_stroke;
    worker->draw_funcs.draw_rop3 = (draw_rop3_t)gl_canvas_draw_rop3;
    worker->draw_funcs.draw_blend = (draw_blend_t)gl_canvas_draw_blend;
    worker->draw_funcs.draw_blackness = (draw_blackness_t)gl_canvas_draw_blackness;
    worker->draw_funcs.draw_whiteness = (draw_whiteness_t)gl_canvas_draw_whiteness;
    worker->draw_funcs.draw_invers = (draw_invers_t)gl_canvas_draw_invers;
    worker->draw_funcs.draw_transparent = (draw_transparent_t)gl_canvas_draw_transparent;
    worker->draw_funcs.draw_alpha_blend = (draw_alpha_blend_t)gl_canvas_draw_alpha_blend;
    worker->draw_funcs.read_pixels = (read_pixels_t)gl_canvas_read_pixels;

    worker->draw_funcs.set_top_mask = (set_top_mask_t)gl_canvas_set_top_mask;
    worker->draw_funcs.clear_top_mask = (clear_top_mask_t)gl_canvas_clear_top_mask;
    worker->draw_funcs.validate_area = (validate_area_t)gl_validate_area;
    worker->draw_funcs.destroy = (destroy_t)destroy_gl_canvas;
}

static GLCanvas *create_ogl_context_common(RedWorker *worker, OGLCtx *ctx, uint32_t width,
                                           uint32_t height, int32_t stride, uint8_t depth)
{
    GLCanvas *canvas;

    oglctx_make_current(ctx);
    if (!(canvas = gl_canvas_create(ctx, width, height, depth, &worker->image_cache,
                                    image_cache_put, image_cache_get, worker,
                                    cb_get_virt_preload_group,
                                    worker, cb_validate_virt_preload_group))) {
        return NULL;
    }

    gl_canvas_clear(canvas);

    return canvas;
}

static GLCanvas *create_ogl_pbuf_context(RedWorker *worker, uint32_t width, uint32_t height,
                                         int32_t stride, uint8_t depth)
{
    OGLCtx *ctx;
    GLCanvas *canvas;

    if (!(ctx = pbuf_create(width, height))) {
        return NULL;
    }

    if (!(canvas = create_ogl_context_common(worker, ctx, width, height, stride, depth))) {
        oglctx_destroy(ctx);
        return NULL;
    }

    return canvas;
}

static GLCanvas *create_ogl_pixmap_context(RedWorker *worker, uint32_t width, uint32_t height,
                                           int32_t stride, uint8_t depth) {
    OGLCtx *ctx;
    GLCanvas *canvas;

    if (!(ctx = pixmap_create(width, height))) {
        return NULL;
    }

    if (!(canvas = create_ogl_context_common(worker, ctx, width, height, stride, depth))) {
        oglctx_destroy(ctx);
        return NULL;
    }

    return canvas;
}

static inline void surface_init_draw_funcs(RedWorker *worker, uint32_t renderer)
{
    switch (renderer) {
    case RED_RENDERER_CAIRO:
        init_cairo_draw_funcs(worker);
        red_printf("using cairo canvas");
        return;
    case RED_RENDERER_OGL_PBUF:
        init_ogl_draw_funcs(worker);
        red_printf("using opengl pbuff canvas");
        return;
    case RED_RENDERER_OGL_PIXMAP:
        init_ogl_draw_funcs(worker);
        red_printf("using opengl pixmap canvas");
        return;
    default:
        red_error("invalid renderer type");
    };
}

static inline void *create_canvas_for_surface(RedWorker *worker, Surface *surface,
                                              uint32_t renderer, uint32_t width, uint32_t height,
                                              int32_t stride, uint8_t depth, void *line_0)
{
    void *canvas;

    switch (renderer) {
    case RED_RENDERER_CAIRO:
        canvas = create_cairo_context(worker, width, height, stride, depth, line_0);
        surface->context.top_down = TRUE;
        return canvas;
    case RED_RENDERER_OGL_PBUF:
        canvas = create_ogl_pbuf_context(worker, width, height, stride, depth);
        surface->context.top_down = FALSE;
        return canvas;
    case RED_RENDERER_OGL_PIXMAP:
        canvas = create_ogl_pixmap_context(worker, width, height, stride, depth);
        surface->context.top_down = FALSE;
        return canvas;
    default:
        red_error("invalid renderer type");
    };
}

static inline void red_create_surface(RedWorker *worker, uint32_t width, uint32_t height,
                                      int32_t stride, uint8_t depth, void *line_0)
{
    uint32_t i;
    Surface *surface = &worker->surface;

    if (stride >= 0) {
        PANIC("Untested path stride >= 0");
    }
    PANIC_ON(surface->context.canvas);

    surface->context.width = width;
    surface->context.height = height;
    surface->context.depth = depth;
    surface->context.stride = stride;
    surface->context.line_0 = line_0;
    surface->refs = 1;

    if (worker->renderer != RED_RENDERER_INVALID) {
        surface->context.canvas = create_canvas_for_surface(worker, surface, worker->renderer,
                                                            width, height, stride,
                                                            surface->context.depth, line_0);
        if (!surface->context.canvas) {
            PANIC("drawing canvas creating failed - can`t create same type canvas");
        }
        return;
    }

    for (i = 0; i < worker->num_renderers; i++) {
        surface->context.canvas = create_canvas_for_surface(worker, surface, worker->renderers[i],
                                                            width, height, stride,
                                                            surface->context.depth, line_0);
        if (surface->context.canvas) {
            worker->renderer = worker->renderers[i];
            surface_init_draw_funcs(worker, worker->renderers[i]);
            return;
        }
    }

    PANIC("unable to create drawing canvas");
}

static void red_wait_outgoiong_item(RedChannel *channel);

static inline void flush_display_commands(RedWorker *worker)
{
    for (;;) {
        uint64_t end_time;

        while (red_process_commands(worker, MAX_PIPE_SIZE)) {
            display_channel_push(worker);
        }

        if (!worker->qxl->has_command(worker->qxl)) {
            break;
        }
        end_time = red_now() + DISPLAY_CLIENT_TIMEOUT * 10;
        int sleep_count = 0;
        for (;;) {
            display_channel_push(worker);
            if (!worker->display_channel ||
                                         worker->display_channel->base.pipe_size <= MAX_PIPE_SIZE) {
                break;
            }
            RedChannel *channel = (RedChannel *)worker->display_channel;
            red_ref_channel(channel);
            red_receive(channel);
            red_send_data(channel, NULL);
            if (red_now() >= end_time) {
                red_printf("update timout");
                red_disconnect_display((RedChannel *)worker->display_channel);
            } else {
                sleep_count++;
                usleep(DISPLAY_CLIENT_RETRY_INTERVAL);
            }
            red_unref_channel(channel);
        }
    }
}

static inline void red_flush_surface_pipe(RedWorker *worker)
{
    if (worker->display_channel) {
        display_channel_push(worker);
    }
}

static void push_new_mode(RedWorker *worker)
{
    DisplayChannel *display_channel;

    if ((display_channel = worker->display_channel)) {
        red_pipe_add_type(&display_channel->base, PIPE_ITEM_TYPE_INVAL_PALLET_CACHE);
        if (!display_channel->base.migrate) {
            red_pipe_add_type(&display_channel->base, PIPE_ITEM_TYPE_MODE);
        }
        display_channel_push(worker);
    }
}

static int display_channel_wait_for_init(DisplayChannel *display_channel)
{
    display_channel->expect_init = TRUE;
    uint64_t end_time = red_now() + DISPLAY_CLIENT_TIMEOUT;
    for (;;) {
        red_receive((RedChannel *)display_channel);
        if (!display_channel->base.peer) {
            break;
        }
        if (display_channel->pixmap_cache && display_channel->glz_dict) {
            display_channel->pixmap_cache_generation = display_channel->pixmap_cache->generation;
            display_channel->glz = glz_encoder_create(display_channel->base.id,
                                                      display_channel->glz_dict->dict,
                                                      &display_channel->glz_data.usr);
            if (!display_channel->glz) {
                PANIC("create global lz failed");
            }
            return TRUE;
        }
        if (red_now() > end_time) {
            red_printf("timeout");
            red_disconnect_display((RedChannel *)display_channel);
            break;
        }
        usleep(DISPLAY_CLIENT_RETRY_INTERVAL);
    }
    return FALSE;
}

static void on_new_display_channel(RedWorker *worker)
{
    DisplayChannel *display_channel = worker->display_channel;
    ASSERT(display_channel);

    red_pipe_add_type(&display_channel->base, PIPE_ITEM_TYPE_SET_ACK);

    if (display_channel->base.migrate) {
        display_channel->expect_migrate_data = TRUE;
        return;
    }

    if (!display_channel_wait_for_init(display_channel)) {
        return;
    }
    display_channel->base.messages_window = 0;
    if (worker->surface.context.canvas) {
        red_current_flush(worker);
        push_new_mode(worker);
        red_add_screen_image(worker);
        if (channel_is_connected(&display_channel->base)) {
            red_pipe_add_verb(&display_channel->base, SPICE_MSG_DISPLAY_MARK);
            red_disply_start_streams(display_channel);
        }
    }
}

static int channel_handle_message(RedChannel *channel, SpiceDataHeader *message)
{
    switch (message->type) {
    case SPICE_MSGC_ACK_SYNC:
        if (message->size != sizeof(uint32_t)) {
            red_printf("bad message size");
            return FALSE;
        }
        channel->client_ack_generation = *(uint32_t *)(message + 1);
        break;
    case SPICE_MSGC_ACK:
        if (channel->client_ack_generation == channel->ack_generation) {
            channel->messages_window -= channel->client_ack_window;
        }
        break;
    case SPICE_MSGC_DISCONNECTING:
        break;
    default:
        red_printf("invalid message type %u", message->type);
        return FALSE;
    }
    return TRUE;
}

static GlzSharedDictionary *_red_find_glz_dictionary(uint8_t dict_id)
{
    RingItem *now;
    GlzSharedDictionary *ret = NULL;

    now = &glz_dictionary_list;

    while ((now = ring_next(&glz_dictionary_list, now))) {
        if (((GlzSharedDictionary *)now)->id == dict_id) {
            ret = (GlzSharedDictionary *)now;
            break;
        }
    }

    return ret;
}

static GlzSharedDictionary *_red_create_glz_dictionary(DisplayChannel *display,
                                                       uint8_t id,
                                                       GlzEncDictContext *opaque_dict)
{
    GlzSharedDictionary *shared_dict = malloc(sizeof(*shared_dict));
    memset(shared_dict, 0, sizeof(*shared_dict)); // nullify the ring base

    if (!shared_dict) {
        return NULL;
    }
    shared_dict->dict = opaque_dict;
    shared_dict->id = id;
    shared_dict->refs = 1;
    shared_dict->migrate_freeze = FALSE;
    ring_item_init(&shared_dict->base);
    pthread_rwlock_init(&shared_dict->encode_lock, NULL);
    return shared_dict;
}

static GlzSharedDictionary *red_create_glz_dictionary(DisplayChannel *display,
                                                      uint8_t id, int window_size)
{
    GlzEncDictContext *glz_dict = glz_enc_dictionary_create(window_size,
                                                            MAX_LZ_ENCODERS,
                                                            &display->glz_data.usr);
#ifdef COMPRESS_DEBUG
    red_printf("Lz Window %d Size=%d", id, window_size);
#endif
    if (!glz_dict) {
        PANIC("failed creating lz dictionary");
        return NULL;
    }
    return _red_create_glz_dictionary(display, id, glz_dict);
}

static GlzSharedDictionary *red_create_restored_glz_dictionary(DisplayChannel *display,
                                                               uint8_t id,
                                                               GlzEncDictRestoreData *restore_data)
{
    GlzEncDictContext *glz_dict = glz_enc_dictionary_restore(restore_data,
                                                             &display->glz_data.usr);
    if (!glz_dict) {
        PANIC("failed creating lz dictionary");
        return NULL;
    }
    return _red_create_glz_dictionary(display, id, glz_dict);
}

static GlzSharedDictionary *red_get_glz_dictionary(DisplayChannel *display,
                                                   uint8_t id, int window_size)
{
    GlzSharedDictionary *shared_dict = NULL;

    pthread_mutex_lock(&glz_dictionary_list_lock);

    shared_dict = _red_find_glz_dictionary(id);

    if (!shared_dict) {
        shared_dict = red_create_glz_dictionary(display, id, window_size);
        ring_add(&glz_dictionary_list, &shared_dict->base);
    } else {
        shared_dict->refs++;
    }
    pthread_mutex_unlock(&glz_dictionary_list_lock);
    return shared_dict;
}

static GlzSharedDictionary *red_restore_glz_dictionary(DisplayChannel *display,
                                                       uint8_t id,
                                                       GlzEncDictRestoreData *restore_data)
{
    GlzSharedDictionary *shared_dict = NULL;

    pthread_mutex_lock(&glz_dictionary_list_lock);

    shared_dict = _red_find_glz_dictionary(id);

    if (!shared_dict) {
        shared_dict = red_create_restored_glz_dictionary(display, id, restore_data);
        ring_add(&glz_dictionary_list, &shared_dict->base);
    } else {
        shared_dict->refs++;
    }
    pthread_mutex_unlock(&glz_dictionary_list_lock);
    return shared_dict;
}

static void red_freeze_glz(DisplayChannel *channel)
{
    pthread_rwlock_wrlock(&channel->glz_dict->encode_lock);
    if (!channel->glz_dict->migrate_freeze) {
        channel->glz_dict->migrate_freeze = TRUE;
    }
    pthread_rwlock_unlock(&channel->glz_dict->encode_lock);
}

/* destroy encoder, and dictionary if no one uses it*/
static void red_release_glz(DisplayChannel *channel)
{
    GlzSharedDictionary *shared_dict;

    red_display_clear_glz_drawables(channel);

    glz_encoder_destroy(channel->glz);
    channel->glz = NULL;

    if (!(shared_dict = channel->glz_dict)) {
        return;
    }

    channel->glz_dict = NULL;
    pthread_mutex_lock(&cache_lock);
    if (--shared_dict->refs) {
        pthread_mutex_unlock(&cache_lock);
        return;
    }
    ring_remove(&shared_dict->base);
    pthread_mutex_unlock(&cache_lock);
    glz_enc_dictionary_destroy(shared_dict->dict, &channel->glz_data.usr);
    free(shared_dict);
}

static PixmapCache *red_create_pixmap_cache(uint8_t id, int64_t size)
{
    PixmapCache *cache = malloc(sizeof(*cache));
    if (!cache) {
        return NULL;
    }
    memset(cache, 0, sizeof(*cache));
    ring_item_init(&cache->base);
    pthread_mutex_init(&cache->lock, NULL);
    cache->id = id;
    cache->refs = 1;
    ring_init(&cache->lru);
    cache->available = size;
    cache->size = size;
    return cache;
}

static PixmapCache *red_get_pixmap_cache(uint8_t id, int64_t size)
{
    PixmapCache *cache = NULL;
    RingItem *now;
    pthread_mutex_lock(&cache_lock);

    now = &pixmap_cache_list;
    while ((now = ring_next(&pixmap_cache_list, now))) {
        if (((PixmapCache *)now)->id == id) {
            cache = (PixmapCache *)now;
            cache->refs++;
            break;
        }
    }
    if (!cache) {
        cache = red_create_pixmap_cache(id, size);
        ring_add(&pixmap_cache_list, &cache->base);
    }
    pthread_mutex_unlock(&cache_lock);
    return cache;
}

static void red_release_pixmap_cache(DisplayChannel *channel)
{
    PixmapCache *cache;
    if (!(cache = channel->pixmap_cache)) {
        return;
    }
    channel->pixmap_cache = NULL;
    pthread_mutex_lock(&cache_lock);
    if (--cache->refs) {
        pthread_mutex_unlock(&cache_lock);
        return;
    }
    ring_remove(&cache->base);
    pthread_mutex_unlock(&cache_lock);
    pixmap_cache_destroy(cache);
    free(cache);
}

static int display_channel_init_cache(DisplayChannel *channel, SpiceMsgcDisplayInit *init_info)
{
    ASSERT(!channel->pixmap_cache);
    return !!(channel->pixmap_cache = red_get_pixmap_cache(init_info->pixmap_cache_id,
                                                           init_info->pixmap_cache_size));
}

static int display_channel_init_glz_dictionary(DisplayChannel *channel, SpiceMsgcDisplayInit *init_info)
{
    ASSERT(!channel->glz_dict);
    ring_init(&channel->glz_drawables);
    ring_init(&channel->glz_drawables_inst_to_free);
    pthread_mutex_init(&channel->glz_drawables_inst_to_free_lock, NULL);
    return !!(channel->glz_dict = red_get_glz_dictionary(channel,
                                                         init_info->glz_dictionary_id,
                                                         init_info->glz_dictionary_window_size));
}

static int display_channel_init(DisplayChannel *channel, SpiceMsgcDisplayInit *init_info)
{
    return (display_channel_init_cache(channel, init_info) &&
            display_channel_init_glz_dictionary(channel, init_info));
}

static int display_channel_handle_migrate_glz_dictionary(DisplayChannel *channel,
                                                         DisplayChannelMigrateData *migrate_info)
{
    ASSERT(!channel->glz_dict);
    ring_init(&channel->glz_drawables);
    ring_init(&channel->glz_drawables_inst_to_free);
    pthread_mutex_init(&channel->glz_drawables_inst_to_free_lock, NULL);
    return !!(channel->glz_dict = red_restore_glz_dictionary(channel,
                                                             migrate_info->glz_dict_id,
                                                             &migrate_info->glz_dict_restore_data));
}

static int display_channel_handle_migrate_mark(DisplayChannel *channel)
{
    if (!channel->expect_migrate_mark) {
        red_printf("unexpected");
        return FALSE;
    }
    channel->expect_migrate_mark = FALSE;
    red_pipe_add_type((RedChannel *)channel, PIPE_ITEM_TYPE_MIGRATE_DATA);
    return TRUE;
}

static int display_channel_handle_migrate_data(DisplayChannel *channel, SpiceDataHeader *message)
{
    DisplayChannelMigrateData *migrate_data;
    int i;

    if (!channel->expect_migrate_data) {
        red_printf("unexpected");
        return FALSE;
    }
    channel->expect_migrate_data = FALSE;
    if (message->size < sizeof(*migrate_data)) {
        red_printf("bad message size");
        return FALSE;
    }
    migrate_data = (DisplayChannelMigrateData *)(message + 1);
    if (migrate_data->magic != DISPLAY_MIGRATE_DATA_MAGIC ||
                                            migrate_data->version != DISPLAY_MIGRATE_DATA_VERSION) {
        red_printf("invalid content");
        return FALSE;
    }
    ASSERT(channel->base.send_data.header.serial == 0);
    channel->base.send_data.header.serial = migrate_data->message_serial;
    if (!(channel->pixmap_cache = red_get_pixmap_cache(migrate_data->pixmap_cache_id, -1))) {
        return FALSE;
    }
    pthread_mutex_lock(&channel->pixmap_cache->lock);
    for (i = 0; i < MAX_CACHE_CLIENTS; i++) {
        channel->pixmap_cache->sync[i] = MAX(channel->pixmap_cache->sync[i],
                                             migrate_data->pixmap_cache_clients[i]);
    }
    pthread_mutex_unlock(&channel->pixmap_cache->lock);

    if (migrate_data->pixmap_cache_freezer) {
        channel->pixmap_cache->size = migrate_data->pixmap_cache_size;
        red_pipe_add_type((RedChannel *)channel, PIPE_ITEM_TYPE_PIXMAP_RESET);
    }

    if (display_channel_handle_migrate_glz_dictionary(channel, migrate_data)) {
        channel->glz = glz_encoder_create(channel->base.id,
                                          channel->glz_dict->dict, &channel->glz_data.usr);
        if (!channel->glz) {
            PANIC("create global lz failed");
        }
    } else {
        PANIC("restoring global lz dictionary failed");
    }

    channel->base.messages_window = 0;
    return TRUE;
}

static int display_channel_handle_message(RedChannel *channel, SpiceDataHeader *message)
{
    switch (message->type) {
    case SPICE_MSGC_DISPLAY_INIT:
        if (message->size != sizeof(SpiceMsgcDisplayInit)) {
            red_printf("bad message size");
            return FALSE;
        }
        if (!((DisplayChannel *)channel)->expect_init) {
            red_printf("unexpected SPICE_MSGC_DISPLAY_INIT");
            return FALSE;
        }
        ((DisplayChannel *)channel)->expect_init = FALSE;
        return display_channel_init((DisplayChannel *)channel, (SpiceMsgcDisplayInit *)(message + 1));
    case SPICE_MSGC_MIGRATE_FLUSH_MARK:
        return display_channel_handle_migrate_mark((DisplayChannel *)channel);
    case SPICE_MSGC_MIGRATE_DATA:
        return display_channel_handle_migrate_data((DisplayChannel *)channel, message);
    default:
        return channel_handle_message(channel, message);
    }
}

static void red_receive(RedChannel *channel)
{
    for (;;) {
        ssize_t n;
        n = channel->recive_data.end - channel->recive_data.now;
        ASSERT(n);
        ASSERT(channel->peer);
        if ((n = channel->peer->cb_read(channel->peer->ctx, channel->recive_data.now, n)) <= 0) {
            if (n == 0) {
                channel->disconnect(channel);
                return;
            }
            ASSERT(n == -1);
            switch (errno) {
            case EAGAIN:
                return;
            case EINTR:
                break;
            case EPIPE:
                channel->disconnect(channel);
                return;
            default:
                red_printf("%s", strerror(errno));
                channel->disconnect(channel);
                return;
            }
        } else {
            channel->recive_data.now += n;
            for (;;) {
                SpiceDataHeader *message = channel->recive_data.message;
                n = channel->recive_data.now - (uint8_t *)message;
                if (n < sizeof(SpiceDataHeader) ||
                    n < sizeof(SpiceDataHeader) + message->size) {
                    break;
                }
                if (!channel->handle_message(channel, message)) {
                    channel->disconnect(channel);
                    return;
                }
                channel->recive_data.message = (SpiceDataHeader *)((uint8_t *)message +
                                                                 sizeof(SpiceDataHeader) +
                                                                 message->size);
            }

            if (channel->recive_data.now == (uint8_t *)channel->recive_data.message) {
                channel->recive_data.now = channel->recive_data.buf;
                channel->recive_data.message = (SpiceDataHeader *)channel->recive_data.buf;
            } else if (channel->recive_data.now == channel->recive_data.end) {
                memcpy(channel->recive_data.buf, channel->recive_data.message, n);
                channel->recive_data.now = channel->recive_data.buf + n;
                channel->recive_data.message = (SpiceDataHeader *)channel->recive_data.buf;
            }
        }
    }
}

static RedChannel *__new_channel(RedWorker *worker, int size, RedsStreamContext *peer, int migrate,
                                 event_listener_action_proc handler,
                                 disconnect_channel_proc disconnect,
                                 hold_item_proc hold_item,
                                 release_item_proc release_item,
                                 handle_message_proc handle_message)
{
    struct epoll_event event;
    RedChannel *channel;
    int flags;
    int delay_val;

    if ((flags = fcntl(peer->socket, F_GETFL)) == -1) {
        red_printf("accept failed, %s", strerror(errno));
        goto error1;
    }

    if (fcntl(peer->socket, F_SETFL, flags | O_NONBLOCK) == -1) {
        red_printf("accept failed, %s", strerror(errno));
        goto error1;
    }

    delay_val = IS_LOW_BANDWIDTH() ? 0 : 1;
    if (setsockopt(peer->socket, IPPROTO_TCP, TCP_NODELAY, &delay_val, sizeof(delay_val)) == -1) {
        red_printf("setsockopt failed, %s", strerror(errno));
    }

    ASSERT(size >= sizeof(*channel));
    if (!(channel = malloc(size))) {
        red_printf("malloc failed");
        goto error1;
    }
    memset(channel, 0, size);
    channel->id = worker->id;
    channel->listener.refs = 1;
    channel->listener.action = handler;
    channel->disconnect = disconnect;
    channel->hold_item = hold_item;
    channel->release_item = release_item;
    channel->handle_message = handle_message;
    channel->peer = peer;
    channel->worker = worker;
    channel->messages_window = ~0;  // blocks send message (maybe use send_data.blocked +
                                    // block flags)
    channel->client_ack_window = IS_LOW_BANDWIDTH() ? WIDE_CLIENT_ACK_WINDOW :
                                                      NARROW_CLIENT_ACK_WINDOW;
    channel->client_ack_generation = ~0;
    channel->recive_data.message = (SpiceDataHeader *)channel->recive_data.buf;
    channel->recive_data.now = channel->recive_data.buf;
    channel->recive_data.end = channel->recive_data.buf + sizeof(channel->recive_data.buf);
    ring_init(&channel->pipe);

    event.events = EPOLLIN | EPOLLOUT | EPOLLET;
    event.data.ptr = channel;
    if (epoll_ctl(worker->epoll, EPOLL_CTL_ADD, peer->socket, &event) == -1) {
        red_printf("epoll_ctl failed, %s", strerror(errno));
        goto error2;
    }

    channel->migrate = migrate;
    return channel;

error2:
    free(channel);
error1:
    peer->cb_free(peer);

    return NULL;
}

static void handle_channel_events(EventListener *in_listener, uint32_t events)
{
    RedChannel *channel = (RedChannel *)in_listener;

    if ((events & EPOLLIN)) {
        red_receive(channel);
    }

    if (channel->send_data.blocked) {
        red_send_data(channel, NULL);
    }
}

static void display_channel_hold_item(void *item)
{
    ASSERT(item);
    switch (((PipeItem *)item)->type) {
    case PIPE_ITEM_TYPE_DRAW:
    case PIPE_ITEM_TYPE_STREAM_CREATE:
        CONTAINEROF(item, Drawable, pipe_item)->refs++;
        break;
    case PIPE_ITEM_TYPE_STREAM_CLIP:
        ((StreamClipItem *)item)->refs++;
        break;
    case PIPE_ITEM_TYPE_UPGRADE:
        ((UpgradeItem *)item)->refs++;
        break;
    case PIPE_ITEM_TYPE_IMAGE:
        ((ImageItem *)item)->refs++;
        break;
    default:
        PANIC("invalid item type");
    }
}

static void display_channel_release_item(RedChannel *channel, void *item)
{
    ASSERT(item);
    switch (((PipeItem *)item)->type) {
    case PIPE_ITEM_TYPE_DRAW:
    case PIPE_ITEM_TYPE_STREAM_CREATE:
        release_drawable(channel->worker, CONTAINEROF(item, Drawable, pipe_item));
        break;
    case PIPE_ITEM_TYPE_STREAM_CLIP:
        red_display_release_stream_clip((DisplayChannel *)channel, (StreamClipItem *)item);
        break;
    case PIPE_ITEM_TYPE_UPGRADE:
        release_upgrade_item(channel->worker, (UpgradeItem *)item);
        break;
    case PIPE_ITEM_TYPE_IMAGE:
        release_image_item((ImageItem *)item);
        break;
    default:
        PANIC("invalid item type");
    }
}

static void handle_new_display_channel(RedWorker *worker, RedsStreamContext *peer, int migrate)
{
    DisplayChannel *display_channel;
    size_t stream_buf_size;

    red_disconnect_display((RedChannel *)worker->display_channel);

    if (!(display_channel = (DisplayChannel *)__new_channel(worker, sizeof(*display_channel), peer,
                                                            migrate, handle_channel_events,
                                                            red_disconnect_display,
                                                            display_channel_hold_item,
                                                            display_channel_release_item,
                                                            display_channel_handle_message))) {
        return;
    }
#ifdef RED_STATISTICS
    display_channel->stat = stat_add_node(worker->stat, "display_channel", TRUE);
    display_channel->base.out_bytes_counter = stat_add_counter(display_channel->stat,
                                                               "out_bytes", TRUE);
    display_channel->cache_hits_counter = stat_add_counter(display_channel->stat,
                                                           "cache_hits", TRUE);
    display_channel->add_to_cache_counter = stat_add_counter(display_channel->stat,
                                                             "add_to_cache", TRUE);
    display_channel->non_cache_counter = stat_add_counter(display_channel->stat,
                                                          "non_cache", TRUE);
#endif
    ring_init(&display_channel->palette_cache_lru);
    display_channel->palette_cache_available = CLIENT_PALETTE_CACHE_SIZE;
    red_display_init_streams(display_channel);

    stream_buf_size = FF_MIN_BUFFER_SIZE + FF_INPUT_BUFFER_PADDING_SIZE;
    if (!(display_channel->send_data.stream_outbuf = malloc(stream_buf_size))) {
        PANIC("alloc failed");
    }
    display_channel->send_data.stream_outbuf_size = FF_MIN_BUFFER_SIZE;
    red_display_share_stream_buf(display_channel);
    red_display_init_glz_data(display_channel);
    worker->display_channel = display_channel;


    if (!(display_channel->send_data.free_list.res = malloc(sizeof(SpiceResorceList) +
                                                            DISPLAY_FREE_LIST_DEFAULT_SIZE *
                                                            sizeof(SpiceResorceID)))) {
        PANIC("free list alloc failed");
    }
    display_channel->send_data.free_list.res_size = DISPLAY_FREE_LIST_DEFAULT_SIZE;
    red_ref_channel((RedChannel*)display_channel);
    on_new_display_channel(worker);
    red_unref_channel((RedChannel*)display_channel);

    stat_compress_init(&display_channel->lz_stat, lz_stat_name);
    stat_compress_init(&display_channel->glz_stat, glz_stat_name);
    stat_compress_init(&display_channel->quic_stat, quic_stat_name);
}

static void red_disconnect_cursor(RedChannel *channel)
{
    if (!channel || !channel->peer) {
        return;
    }

    ASSERT(channel == (RedChannel *)channel->worker->cursor_channel);
    channel->worker->cursor_channel = NULL;
    red_reset_cursor_cache((CursorChannel *)channel);
    red_disconnect_channel(channel);
}

static void red_migrate_cursor(RedWorker *worker)
{
    if (worker->cursor_channel) {
        red_pipe_add_type(&worker->cursor_channel->base, PIPE_ITEM_TYPE_INVAL_CURSOR_CACHE);
        red_pipe_add_type(&worker->cursor_channel->base, PIPE_ITEM_TYPE_MIGRATE);
    }
}

static void on_new_cursor_channel(RedWorker *worker)
{
    CursorChannel *channel = worker->cursor_channel;

    ASSERT(channel);

    channel->base.messages_window = 0;
    red_pipe_add_type(&channel->base, PIPE_ITEM_TYPE_SET_ACK);
    if (worker->surface.context.canvas && !channel->base.migrate) {
        red_pipe_add_type(&worker->cursor_channel->base, PIPE_ITEM_TYPE_CURSOR_INIT);
    }
}

static void cursor_channel_hold_item(void *item)
{
    ASSERT(item);
    ((CursorItem *)item)->refs++;
}

static void cursor_channel_release_item(RedChannel *channel, void *item)
{
    ASSERT(item);
    red_release_cursor(channel->worker, item);
}

static void red_connect_cursor(RedWorker *worker, RedsStreamContext *peer, int migrate)
{
    CursorChannel *channel;

    red_disconnect_cursor((RedChannel *)worker->cursor_channel);

    if (!(channel = (CursorChannel *)__new_channel(worker, sizeof(*channel), peer, migrate,
                                                   handle_channel_events,
                                                   red_disconnect_cursor,
                                                   cursor_channel_hold_item,
                                                   cursor_channel_release_item,
                                                   channel_handle_message))) {
        return;
    }
#ifdef RED_STATISTICS
    channel->stat = stat_add_node(worker->stat, "cursor_channel", TRUE);
    channel->base.out_bytes_counter = stat_add_counter(channel->stat, "out_bytes", TRUE);
#endif
    ring_init(&channel->cursor_cache_lru);
    channel->cursor_cache_available = CLIENT_CURSOR_CACHE_SIZE;
    worker->cursor_channel = channel;
    on_new_cursor_channel(worker);
}

typedef struct __attribute__ ((__packed__)) CursorData {
    uint32_t visible;
    SpicePoint16 position;
    uint16_t trail_length;
    uint16_t trail_frequency;
    uint32_t data_size;
    SpiceCursor _cursor;
} CursorData;

static void red_save_cursor(RedWorker *worker)
{
    CursorData *cursor_data;
    LocalCursor *local;
    int size;

    ASSERT(worker->cursor);
    ASSERT(worker->cursor->type == CURSOR_TYPE_LOCAL);

    local = (LocalCursor *)worker->cursor;
    size = sizeof(CursorData) + sizeof(SpiceCursor) + local->data_size;
    cursor_data = malloc(size);
    ASSERT(cursor_data);

    cursor_data->position = worker->cursor_position;
    cursor_data->visible = worker->cursor_visible;
    cursor_data->trail_frequency = worker->cursor_trail_frequency;
    cursor_data->trail_length = worker->cursor_trail_length;
    cursor_data->data_size = local->data_size;
    cursor_data->_cursor.header = local->red_cursor.header;
    memcpy(cursor_data->_cursor.data, local->red_cursor.data, local->data_size);
    worker->qxl->set_save_data(worker->qxl, cursor_data, size);
}

static LocalCursor *_new_local_cursor(SpiceCursorHeader *header, int data_size, SpicePoint16 position)
{
    LocalCursor *local;

    local = (LocalCursor *)malloc(sizeof(LocalCursor) + data_size);
    if (!local) {
        return NULL;
    }

    red_pipe_item_init(&local->base.pipe_data, PIPE_ITEM_TYPE_LOCAL_CURSOR);
    local->base.refs = 1;
    local->base.type = CURSOR_TYPE_LOCAL;

    local->red_cursor.header = *header;
    local->red_cursor.header.unique = 0;
    local->red_cursor.flags = 0;
    local->position = position;
    local->data_size = data_size;
    return local;
}

static void red_cursor_flush(RedWorker *worker)
{
    QXLCursorCmd *cursor_cmd;
    QXLCursor *qxl_cursor;
    LocalCursor *local;
    uint32_t data_size;
    QXLDataChunk *chunk;
    uint8_t *dest;

    if (!worker->cursor || worker->cursor->type == CURSOR_TYPE_LOCAL) {
        return;
    }

    ASSERT(worker->cursor->type == CURSOR_TYPE_DEV);

    cursor_cmd = worker->cursor->qxl_cursor;
    ASSERT(cursor_cmd->type == QXL_CURSOR_SET);
    qxl_cursor = (QXLCursor *)get_virt(worker, cursor_cmd->u.set.shape, sizeof(QXLCursor),
                                       worker->cursor->group_id);

    local = _new_local_cursor(&qxl_cursor->header, qxl_cursor->data_size,
                              worker->cursor_position);
    ASSERT(local);
    data_size = local->data_size;
    dest = local->red_cursor.data;
    chunk = &qxl_cursor->chunk;

    while (data_size) {
        ASSERT(chunk);
        ASSERT(chunk->data_size <= data_size);
        memcpy(dest, chunk->data, chunk->data_size);
        data_size -= chunk->data_size;
        dest += chunk->data_size;
        chunk = chunk->next_chunk ?
                (QXLDataChunk *)get_virt(worker, chunk->next_chunk, sizeof(QXLDataChunk),
                                         worker->internal_groupslot_id) : NULL;
    }
    red_set_cursor(worker, &local->base);
    red_release_cursor(worker, &local->base);
}

static void red_save(RedWorker *worker)
{
    if (!worker->cursor) {
        worker->qxl->set_save_data(worker->qxl, NULL, 0);
        return;
    }
    red_save_cursor(worker);
}

static void red_cursor_load(RedWorker *worker)
{
    CursorData *cursor_data = worker->qxl->get_save_data(worker->qxl);
    LocalCursor *local;

    if (!cursor_data) {
        return;
    }

    worker->cursor_position = cursor_data->position;
    worker->cursor_visible = cursor_data->visible;
    worker->cursor_trail_frequency = cursor_data->trail_frequency;
    worker->cursor_trail_length = cursor_data->trail_length;

    local = _new_local_cursor(&cursor_data->_cursor.header, cursor_data->data_size,
                              cursor_data->position);
    ASSERT(local);
    memcpy(local->red_cursor.data, cursor_data->_cursor.data, cursor_data->data_size);
    red_set_cursor(worker, &local->base);
    red_release_cursor(worker, &local->base);
}

static void red_wait_outgoiong_item(RedChannel *channel)
{
    uint64_t end_time;
    int blocked;

    if (!channel || !channel->send_data.blocked) {
        return;
    }
    red_ref_channel(channel);

    end_time = red_now() + DETACH_TIMEOUT;
    red_printf("blocked");

    do {
        usleep(DETACH_SLEEP_DURATION);
        red_receive(channel);
        red_send_data(channel, NULL);
    } while ((blocked = channel->send_data.blocked) && red_now() < end_time);

    if (blocked) {
        red_printf("timeout");
        channel->disconnect(channel);
    }
    red_unref_channel(channel);
}

static inline void handle_dev_update(RedWorker *worker)
{
    RedWorkeMessage message;

    ASSERT(worker->surface.context.canvas && worker->running);

    flush_display_commands(worker);

    red_update_area(worker, worker->qxl->get_update_area(worker->qxl));
    message = RED_WORKER_MESSAGE_READY;
    write_message(worker->channel, &message);
}


static inline void handle_dev_add_memslot(RedWorker *worker)
{
    RedWorkeMessage message;
    QXLDevMemSlot dev_slot;

    receive_data(worker->channel, &dev_slot, sizeof(QXLDevMemSlot));

    ASSERT(worker->num_memslots_groups > dev_slot.slot_group_id);
    ASSERT(worker->num_memslots > dev_slot.slot_id);
    worker->mem_slots[dev_slot.slot_group_id][dev_slot.slot_id].address_delta = dev_slot.addr_delta;
    worker->mem_slots[dev_slot.slot_group_id][dev_slot.slot_id].virt_start_addr =
                                                                                dev_slot.virt_start;
    worker->mem_slots[dev_slot.slot_group_id][dev_slot.slot_id].virt_end_addr = dev_slot.virt_end;
    worker->mem_slots[dev_slot.slot_group_id][dev_slot.slot_id].generation = dev_slot.generation;

    message = RED_WORKER_MESSAGE_READY;
    write_message(worker->channel, &message);
}

static inline void handle_dev_del_memslot(RedWorker *worker)
{
    uint32_t slot_id;
    uint32_t slot_group_id;

    receive_data(worker->channel, &slot_group_id, sizeof(uint32_t));
    receive_data(worker->channel, &slot_id, sizeof(uint32_t));

    ASSERT(worker->num_memslots_groups > slot_group_id);
    ASSERT(worker->num_memslots > slot_id);

    worker->mem_slots[slot_group_id][slot_id].virt_start_addr = 0;
    worker->mem_slots[slot_group_id][slot_id].virt_end_addr = 0;
}

static inline void destroy_surface_wait(RedWorker *worker)
{
    flush_display_commands(worker);
    red_flush_surface_pipe(worker);
    red_display_clear_glz_drawables(worker->display_channel);
    red_current_clear(worker);
    red_wait_outgoiong_item((RedChannel *)worker->display_channel);
    if (worker->display_channel) {
        ASSERT(!worker->display_channel->base.send_data.item);
    }
}

static inline void handle_dev_destroy_surface_wait(RedWorker *worker)
{
    RedWorkeMessage message;
    uint32_t surface_id;

    receive_data(worker->channel, &surface_id, sizeof(uint32_t));

    ASSERT(surface_id == 0);

    if (worker->surface.context.canvas) {
        destroy_surface_wait(worker);
    }

    message = RED_WORKER_MESSAGE_READY;
    write_message(worker->channel, &message);
}

static inline void handle_dev_destroy_surfaces(RedWorker *worker)
{
    RedWorkeMessage message;

    destroy_surface_wait(worker);
    __red_destroy_surface(worker);
    ASSERT(ring_is_empty(&worker->streams));

    red_wait_outgoiong_item((RedChannel *)worker->cursor_channel);
    if (worker->cursor_channel) {
        red_pipe_add_type(&worker->cursor_channel->base, PIPE_ITEM_TYPE_INVAL_CURSOR_CACHE);
        if (!worker->cursor_channel->base.migrate) {
            red_pipe_add_verb(&worker->cursor_channel->base, SPICE_MSG_CURSOR_RESET);
        }
        ASSERT(!worker->cursor_channel->base.send_data.item);
    }

    if (worker->display_channel) {
        red_pipe_add_type(&worker->display_channel->base, PIPE_ITEM_TYPE_INVAL_PALLET_CACHE);
        red_pipe_add_verb(&worker->display_channel->base, SPICE_MSG_DISPLAY_STREAM_DESTROY_ALL);
        if (!worker->display_channel->base.migrate) {
            red_pipe_add_verb(&worker->display_channel->base, SPICE_MSG_DISPLAY_RESET);
        }
    }

    ASSERT(!worker->surface.context.canvas);

    worker->cursor_visible = TRUE;
    worker->cursor_position.x = worker->cursor_position.y = 0;
    worker->cursor_trail_length = worker->cursor_trail_frequency = 0;

    message = RED_WORKER_MESSAGE_READY;
    write_message(worker->channel, &message);
}

static inline void handle_dev_create_primary_surface(RedWorker *worker)
{
    RedWorkeMessage message;
    uint32_t surface_id;
    QXLDevSurfaceCreate surface;
    uint8_t *line_0;

    receive_data(worker->channel, &surface_id, sizeof(uint32_t));
    receive_data(worker->channel, &surface, sizeof(QXLDevSurfaceCreate));

    PANIC_ON(surface_id != 0);
    PANIC_ON(surface.height == 0);
    PANIC_ON(((uint64_t)abs(surface.stride) * (uint64_t)surface.height) !=
             abs(surface.stride) * surface.height);

    line_0 = (uint8_t*)get_virt(worker, surface.mem, surface.height * abs(surface.stride),
                                surface.group_id);
    if (surface.stride < 0) {
        line_0 -= (int32_t)(surface.stride * (surface.height -1));
    }

    red_create_surface(worker, surface.width, surface.height, surface.stride, surface.depth,
                       line_0);

    if (worker->display_channel) {
        red_pipe_add_type(&worker->display_channel->base, PIPE_ITEM_TYPE_MODE);
        red_pipe_add_verb(&worker->display_channel->base, SPICE_MSG_DISPLAY_MARK);
        display_channel_push(worker);
    }

    if (worker->cursor_channel) {
        red_pipe_add_type(&worker->cursor_channel->base, PIPE_ITEM_TYPE_CURSOR_INIT);
    }

    message = RED_WORKER_MESSAGE_READY;
    write_message(worker->channel, &message);
}

static inline void handle_dev_destroy_primary_surface(RedWorker *worker)
{
    RedWorkeMessage message;
    uint32_t surface_id;

    receive_data(worker->channel, &surface_id, sizeof(uint32_t));

    PANIC_ON(surface_id != 0);

    if (worker->cursor) {
        red_release_cursor(worker, worker->cursor);
        worker->cursor = NULL;
    }

    red_wait_outgoiong_item((RedChannel *)worker->cursor_channel);
    if (worker->cursor_channel) {
        red_pipe_add_type(&worker->cursor_channel->base, PIPE_ITEM_TYPE_INVAL_CURSOR_CACHE);
        if (!worker->cursor_channel->base.migrate) {
            red_pipe_add_verb(&worker->cursor_channel->base, SPICE_MSG_CURSOR_RESET);
        }
        ASSERT(!worker->cursor_channel->base.send_data.item);
    }


    destroy_surface_wait(worker);
    red_destroy_surface(worker);
    ASSERT(ring_is_empty(&worker->streams));

    ASSERT(!worker->surface.context.canvas);

    worker->cursor_visible = TRUE;
    worker->cursor_position.x = worker->cursor_position.y = 0;
    worker->cursor_trail_length = worker->cursor_trail_frequency = 0;

    message = RED_WORKER_MESSAGE_READY;
    write_message(worker->channel, &message);
}

static void inline red_create_mem_slots(RedWorker *worker)
{
    uint32_t i;

    ASSERT(worker->num_memslots > 0);
    ASSERT(worker->num_memslots_groups > 0);
    worker->mem_slots = (MemSlot **)malloc(sizeof(MemSlot *) * worker->num_memslots_groups);
    PANIC_ON(!worker->mem_slots);

    for (i = 0; i <  worker->num_memslots_groups; ++i) {
        worker->mem_slots[i] = malloc(sizeof(MemSlot) * worker->num_memslots);
        PANIC_ON(!worker->mem_slots[i]);
        memset(worker->mem_slots[i], 0, sizeof(MemSlot) * worker->num_memslots);
    }

    worker->memslot_id_shift = 64 - worker->mem_slot_bits;
    worker->memslot_gen_shift = 64 - (worker->mem_slot_bits + worker->generation_bits);
    worker->memslot_gen_mask = ~((unsigned long)-1 << worker->generation_bits);
    worker->memslot_clean_virt_mask = (((unsigned long)(-1)) >>
                                       (worker->mem_slot_bits + worker->generation_bits));
}

static void handle_dev_input(EventListener *listener, uint32_t events)
{
    RedWorker *worker = CONTAINEROF(listener, RedWorker, dev_listener);
    RedWorkeMessage message;

    read_message(worker->channel, &message);

    switch (message) {
    case RED_WORKER_MESSAGE_UPDATE:
        handle_dev_update(worker);
        break;
    case RED_WORKER_MESSAGE_WAKEUP:
        clear_bit(RED_WORKER_PENDING_WAKEUP, worker->pending);
        stat_inc_counter(worker->wakeup_counter, 1);
        break;
    case RED_WORKER_MESSAGE_OOM:
        ASSERT(worker->running);
        while (red_process_commands(worker, MAX_PIPE_SIZE)) {
            display_channel_push(worker);
        }
        if (worker->qxl->flush_resources(worker->qxl) == 0) {
            red_printf("oom current %u pipe %u", worker->current_size, worker->display_channel ?
                       worker->display_channel->base.pipe_size : 0);
            red_free_some(worker);
        }
        clear_bit(RED_WORKER_PENDING_OOM, worker->pending);
        break;
    case RED_WORKER_MESSAGE_RESET_CURSOR:
        if (worker->cursor) {
            red_release_cursor(worker, worker->cursor);
            worker->cursor = NULL;
        }

        red_wait_outgoiong_item((RedChannel *)worker->cursor_channel);
        if (worker->cursor_channel) {
            red_pipe_add_type(&worker->cursor_channel->base, PIPE_ITEM_TYPE_INVAL_CURSOR_CACHE);
            if (!worker->cursor_channel->base.migrate) {
                red_pipe_add_verb(&worker->cursor_channel->base, SPICE_MSG_CURSOR_RESET);
            }
            ASSERT(!worker->cursor_channel->base.send_data.item);

            worker->cursor_visible = TRUE;
            worker->cursor_position.x = worker->cursor_position.y = 0;
            worker->cursor_trail_length = worker->cursor_trail_frequency = 0;
        }

        message = RED_WORKER_MESSAGE_READY;
        write_message(worker->channel, &message);
        break;
    case RED_WORKER_MESSAGE_RESET_IMAGE_CACHE:
        image_cache_reset(&worker->image_cache);
        message = RED_WORKER_MESSAGE_READY;
        write_message(worker->channel, &message);
        break;
    case RED_WORKER_MESSAGE_DESTROY_SURFACE_WAIT:
        handle_dev_destroy_surface_wait(worker);
        break;
    case RED_WORKER_MESSAGE_DESTROY_SURFACES:
        handle_dev_destroy_surfaces(worker);
        break;
    case RED_WORKER_MESSAGE_CREATE_PRIMARY_SURFACE:
        handle_dev_create_primary_surface(worker);
        break;
    case RED_WORKER_MESSAGE_DESTROY_PRIMARY_SURFACE:
        handle_dev_destroy_primary_surface(worker);
        break;
    case RED_WORKER_MESSAGE_DISPLAY_CONNECT: {
        RedsStreamContext *peer;
        int migrate;
        red_printf("connect");

        receive_data(worker->channel, &peer, sizeof(RedsStreamContext *));
        receive_data(worker->channel, &migrate, sizeof(int));
        handle_new_display_channel(worker, peer, migrate);
        break;
    }
    case RED_WORKER_MESSAGE_DISPLAY_DISCONNECT:
        red_printf("disconnect");
        red_disconnect_display((RedChannel *)worker->display_channel);
        break;
    case RED_WORKER_MESSAGE_SAVE:
        red_printf("save");
        ASSERT(!worker->running);
        red_save(worker);
        message = RED_WORKER_MESSAGE_READY;
        write_message(worker->channel, &message);
        break;
    case RED_WORKER_MESSAGE_LOAD:
        red_printf("load");
        ASSERT(!worker->running);
        red_add_screen_image(worker);
        red_cursor_load(worker);
        message = RED_WORKER_MESSAGE_READY;
        write_message(worker->channel, &message);
        break;
    case RED_WORKER_MESSAGE_STOP: {
        red_printf("stop");
        ASSERT(worker->running);
        worker->running = FALSE;
        red_display_clear_glz_drawables(worker->display_channel);
        red_current_flush(worker);
        red_cursor_flush(worker);
        red_wait_outgoiong_item((RedChannel *)worker->display_channel);
        red_wait_outgoiong_item((RedChannel *)worker->cursor_channel);
        message = RED_WORKER_MESSAGE_READY;
        write_message(worker->channel, &message);
        break;
    }
    case RED_WORKER_MESSAGE_START:
        red_printf("start");
        ASSERT(!worker->running);
        if (worker->cursor_channel) {
            worker->cursor_channel->base.migrate = FALSE;
        }
        if (worker->display_channel) {
            worker->display_channel->base.migrate = FALSE;
        }
        worker->running = TRUE;
        break;
    case RED_WORKER_MESSAGE_DISPLAY_MIGRATE:
        red_printf("migrate");
        red_migrate_display(worker);
        break;
    case RED_WORKER_MESSAGE_CURSOR_CONNECT: {
        RedsStreamContext *peer;
        int migrate;

        red_printf("cursor connect");
        receive_data(worker->channel, &peer, sizeof(RedsStreamContext *));
        receive_data(worker->channel, &migrate, sizeof(int));
        red_connect_cursor(worker, peer, migrate);
        break;
    }
    case RED_WORKER_MESSAGE_CURSOR_DISCONNECT:
        red_printf("cursor disconnect");
        red_disconnect_cursor((RedChannel *)worker->cursor_channel);
        break;
    case RED_WORKER_MESSAGE_CURSOR_MIGRATE:
        red_printf("cursor migrate");
        red_migrate_cursor(worker);
        break;
    case RED_WORKER_MESSAGE_SET_COMPRESSION:
        receive_data(worker->channel, &worker->image_compression, sizeof(image_compression_t));
        switch (worker->image_compression) {
        case IMAGE_COMPRESS_AUTO_LZ:
            red_printf("ic auto_lz");
            break;
        case IMAGE_COMPRESS_AUTO_GLZ:
            red_printf("ic auto_glz");
            break;
        case IMAGE_COMPRESS_QUIC:
            red_printf("ic quic");
            break;
        case IMAGE_COMPRESS_LZ:
            red_printf("ic lz");
            break;
        case IMAGE_COMPRESS_GLZ:
            red_printf("ic glz");
            break;
        case IMAGE_COMPRESS_OFF:
            red_printf("ic off");
            break;
        default:
            red_printf("ic invalid");
        }
#ifdef COMPRESS_STAT
        print_compress_stats(worker->display_channel);
        if (worker->display_channel) {
            stat_reset(&worker->display_channel->quic_stat);
            stat_reset(&worker->display_channel->lz_stat);
            stat_reset(&worker->display_channel->glz_stat);
        }
#endif
        break;
    case RED_WORKER_MESSAGE_SET_STREAMING_VIDEO:
        receive_data(worker->channel, &worker->streaming_video, sizeof(uint32_t));
        ASSERT(worker->streaming_video != STREAM_VIDEO_INVALID);
        switch(worker->streaming_video) {
            case STREAM_VIDEO_ALL:
                red_printf("sv all");
                break;
            case STREAM_VIDEO_FILTER:
                red_printf("sv filter");
                break;
            case STREAM_VIDEO_OFF:
                red_printf("sv off");
                break;
            default:
                red_printf("sv invalid");
        }
        break;
    case RED_WORKER_MESSAGE_SET_MOUSE_MODE:
        receive_data(worker->channel, &worker->mouse_mode, sizeof(uint32_t));
        red_printf("mouse mode %u", worker->mouse_mode);
        break;
    case RED_WORKER_MESSAGE_ADD_MEMSLOT:
        handle_dev_add_memslot(worker);
        break;
    case RED_WORKER_MESSAGE_DEL_MEMSLOT:
        handle_dev_del_memslot(worker);
        break;
    case RED_WORKER_MESSAGE_RESET_MEMSLOTS: {
        uint32_t i;
        for (i = 0; i <  worker->num_memslots_groups; ++i) {
            memset(worker->mem_slots[i], 0, sizeof(MemSlot) * worker->num_memslots);
        }
        break;
    }
    default:
        red_error("message error");
    }
}

static void red_init(RedWorker *worker, WorkerInitData *init_data)
{
    struct epoll_event event;
    RedWorkeMessage message;
    int epoll;

    ASSERT(sizeof(CursorItem) <= QXL_CURSUR_DEVICE_DATA_SIZE);

    memset(worker, 0, sizeof(RedWorker));
    worker->qxl = init_data->qxl_interface;
    worker->id = init_data->id;
    worker->channel = init_data->channel;
    worker->pending = init_data->pending;
    worker->dev_listener.refs = 1;
    worker->dev_listener.action = handle_dev_input;
    worker->cursor_visible = TRUE;
    ASSERT(init_data->num_renderers > 0);
    worker->num_renderers = init_data->num_renderers;
    memcpy(worker->renderers, init_data->renderers, sizeof(worker->renderers));
    worker->renderer = RED_RENDERER_INVALID;
    worker->mouse_mode = SPICE_MOUSE_MODE_SERVER;
    worker->image_compression = init_data->image_compression;
    worker->streaming_video = init_data->streaming_video;
    ring_init(&worker->current_list);
    ring_init(&worker->current);
    image_cache_init(&worker->image_cache);
    drawables_init(worker);
    cursor_items_init(worker);
    red_init_streams(worker);
    stat_init(&worker->add_stat, add_stat_name);
    stat_init(&worker->exclude_stat, exclude_stat_name);
    stat_init(&worker->__exclude_stat, __exclude_stat_name);
#ifdef RED_STATISTICS
    char worker_str[20];
    sprintf(worker_str, "display[%d]", worker->id);
    worker->stat = stat_add_node(INVALID_STAT_REF, worker_str, TRUE);
    worker->wakeup_counter = stat_add_counter(worker->stat, "wakeups", TRUE);
    worker->command_counter = stat_add_counter(worker->stat, "commands", TRUE);
#endif
    if ((epoll = epoll_create(MAX_EPOLL_SOURCES)) == -1) {
        red_error("epoll_create failed, %s", strerror(errno));
    }
    worker->epoll = epoll;

    event.events = EPOLLIN;
    event.data.ptr = &worker->dev_listener;

    if (epoll_ctl(epoll, EPOLL_CTL_ADD, worker->channel, &event) == -1) {
        red_error("add channel failed, %s", strerror(errno));
    }

    worker->num_memslots_groups = init_data->num_memslots_groups;
    worker->num_memslots = init_data->num_memslots;
    worker->generation_bits = init_data->memslot_gen_bits;
    worker->mem_slot_bits = init_data->memslot_id_bits;
    worker->internal_groupslot_id = init_data->internal_groupslot_id;
    red_create_mem_slots(worker);

    message = RED_WORKER_MESSAGE_READY;
    write_message(worker->channel, &message);
}

void *red_worker_main(void *arg)
{
    RedWorker worker;

    red_printf("begin");
    ASSERT(MAX_PIPE_SIZE > WIDE_CLIENT_ACK_WINDOW &&
           MAX_PIPE_SIZE > NARROW_CLIENT_ACK_WINDOW); //ensure wakeup by ack message
    ASSERT(QXL_BITMAP_TOP_DOWN == SPICE_BITMAP_FLAGS_TOP_DOWN);

#if  defined(RED_WORKER_STAT) || defined(COMPRESS_STAT)
    if (pthread_getcpuclockid(pthread_self(), &clock_id)) {
        red_error("pthread_getcpuclockid failed");
    }
#endif

    avcodec_init();
    avcodec_register_all();
    red_init(&worker, (WorkerInitData *)arg);
    red_init_quic(&worker);
    red_init_lz(&worker);
    worker.epoll_timeout = INF_EPOLL_WAIT;
    for (;;) {
        struct epoll_event events[MAX_EPOLL_SOURCES];
        int num_events;
        struct epoll_event *event;
        struct epoll_event *end;

        worker.epoll_timeout = MIN(red_get_streams_timout(&worker), worker.epoll_timeout);
        num_events = epoll_wait(worker.epoll, events, MAX_EPOLL_SOURCES, worker.epoll_timeout);
        red_handle_streams_timout(&worker);

        if (worker.display_channel && worker.display_channel->glz_dict) {
            /* during migration, in the dest, the display channel can be initialized
               while the global lz data not since migrate data msg hasn't been
               recieved yet */
            red_display_handle_glz_drawables_to_free(worker.display_channel);
        }

        worker.epoll_timeout = INF_EPOLL_WAIT;
        if (num_events == -1) {
            if (errno != EINTR) {
                red_error("poll_wait failed, %s", strerror(errno));
            }
            num_events = 0;
        }

        for (event = events, end = event + num_events;  event < end; event++) {
            EventListener *evt_listener = (EventListener *)event->data.ptr;
            evt_listener->refs++;
        }

        for (event = events, end = event + num_events; event < end; event++) {
            EventListener *evt_listener = (EventListener *)event->data.ptr;

            if (evt_listener->refs > 1) {
                evt_listener->action(evt_listener, event->events);
                if (--evt_listener->refs) {
                    continue;
                }
            }
            free(evt_listener);
        }

        if (worker.running) {
            red_process_cursor(&worker, MAX_PIPE_SIZE);
            red_process_commands(&worker, MAX_PIPE_SIZE);
        }
        red_push(&worker);
    }
    red_printf("exit");
    return 0;
}

#ifdef DUMP_BITMAP
#include <stdio.h>
static void dump_palette(FILE *f, SpicePalette* plt)
{
    int i;
    for (i = 0; i < plt->num_ents; i++) {
        fwrite(plt->ents + i, sizeof(uint32_t), 1, f);
    }
}

static void dump_line(FILE *f, uint8_t* line, uint16_t n_pixel_bits, int width, int row_size)
{
    int i;
    int copy_bytes_size = ALIGN(n_pixel_bits * width, 8) / 8;

    fwrite(line, 1, copy_bytes_size, f);
    if (row_size > copy_bytes_size) {
        // each line should be 4 bytes aligned
        for (i = copy_bytes_size; i < row_size; i++) {
            fprintf(f, "%c", 0);
        }
    }
}

#define RAM_PATH "/tmp/tmpfs"

static void dump_bitmap(RedWorker *worker, SpiceBitmap *bitmap, uint32_t group_id)
{
    static uint32_t file_id = 0;

    char file_str[200];
    int rgb = TRUE;
    uint16_t n_pixel_bits;
    SpicePalette *plt = NULL;
    uint32_t id;
    int row_size;
    uint32_t file_size;
    int alpha = 0;
    uint32_t header_size = 14 + 40;
    uint32_t bitmap_data_offset;
    uint32_t tmp_u32;
    int32_t tmp_32;
    uint16_t tmp_u16;
    FILE *f;

    switch (bitmap->format) {
    case SPICE_BITMAP_FMT_1BIT_BE:
    case SPICE_BITMAP_FMT_1BIT_LE:
        rgb = FALSE;
        n_pixel_bits = 1;
        break;
    case SPICE_BITMAP_FMT_4BIT_BE:
    case SPICE_BITMAP_FMT_4BIT_LE:
        rgb = FALSE;
        n_pixel_bits = 4;
        break;
    case SPICE_BITMAP_FMT_8BIT:
        rgb = FALSE;
        n_pixel_bits = 8;
        break;
    case SPICE_BITMAP_FMT_16BIT:
        n_pixel_bits = 16;
        break;
    case SPICE_BITMAP_FMT_24BIT:
        n_pixel_bits = 24;
        break;
    case SPICE_BITMAP_FMT_32BIT:
        n_pixel_bits = 32;
        break;
    case SPICE_BITMAP_FMT_RGBA:
        n_pixel_bits = 32;
        alpha = 1;
        break;
    default:
        red_error("invalid bitmap format  %u", bitmap->format);
    }

    if (!rgb) {
        if (!bitmap->palette) {
            return; // dont dump masks.
        }
        plt = (SpicePalette *)get_virt(worker, bitmap->palette, sizeof(SpicePalette), group_id);
    }
    row_size = (((bitmap->x * n_pixel_bits) + 31) / 32) * 4;
    bitmap_data_offset = header_size;

    if (plt) {
        bitmap_data_offset += plt->num_ents * 4;
    }
    file_size = bitmap_data_offset + (bitmap->y * row_size);

    id = ++file_id;
    sprintf(file_str, "%s/%u.bmp", RAM_PATH, id);

    f = fopen(file_str, "wb");
    if (!f) {
        red_error("Error creating bmp\n");
        return;
    }

    /* writing the bmp v3 header */
    fprintf(f, "BM");
    fwrite(&file_size, sizeof(file_size), 1, f);
    tmp_u16 = alpha ? 1 : 0;
    fwrite(&tmp_u16, sizeof(tmp_u16), 1, f); // reserved for application
    tmp_u16 = 0;
    fwrite(&tmp_u16, sizeof(tmp_u16), 1, f);
    fwrite(&bitmap_data_offset, sizeof(bitmap_data_offset), 1, f);
    tmp_u32 = header_size - 14;
    fwrite(&tmp_u32, sizeof(tmp_u32), 1, f); // sub header size
    tmp_32 = bitmap->x;
    fwrite(&tmp_32, sizeof(tmp_32), 1, f);
    tmp_32 = bitmap->y;
    fwrite(&tmp_32, sizeof(tmp_32), 1, f);

    tmp_u16 = 1;
    fwrite(&tmp_u16, sizeof(tmp_u16), 1, f); // color plane
    fwrite(&n_pixel_bits, sizeof(n_pixel_bits), 1, f); // pixel depth

    tmp_u32 = 0;
    fwrite(&tmp_u32, sizeof(tmp_u32), 1, f); // compression method

    tmp_u32 = 0; //file_size - bitmap_data_offset;
    fwrite(&tmp_u32, sizeof(tmp_u32), 1, f); // image size
    tmp_32 = 0;
    fwrite(&tmp_32, sizeof(tmp_32), 1, f);
    fwrite(&tmp_32, sizeof(tmp_32), 1, f);
    tmp_u32 = (!plt) ? 0 : plt->num_ents; // plt entries
    fwrite(&tmp_u32, sizeof(tmp_u32), 1, f);
    tmp_u32 = 0;
    fwrite(&tmp_u32, sizeof(tmp_u32), 1, f);

    if (plt) {
        dump_palette(f, plt);
    }
    /* writing the data */
    if ((bitmap->flags & QXL_BITMAP_DIRECT)) {
        uint8_t *lines = (uint8_t*)get_virt(worker, bitmap->data, bitmap->stride * bitmap->y,
                                            group_id);
        int i;
        for (i = 0; i < bitmap->y; i++) {
            dump_line(f, lines + (i * bitmap->stride), n_pixel_bits, bitmap->x, row_size);
        }
    } else {
        QXLDataChunk *chunk = NULL;
        int num_lines;
        SPICE_ADDRESS relative_address = bitmap->data;

        while (relative_address) {
            int i;
            chunk = (QXLDataChunk *)get_virt(worker, relative_address, sizeof(QXLDataChunk),
                                             group_id);
            validate_virt(worker, chunk->data, get_memslot_id(worker, relative_address),
                          chunk->data_size, group_id);
            num_lines = chunk->data_size / bitmap->stride;
            for (i = 0; i < num_lines; i++) {
                dump_line(f, chunk->data + (i * bitmap->stride), n_pixel_bits, bitmap->x, row_size);
            }
            relative_address = chunk->next_chunk;
        }
    }
    fclose(f);
}

#endif