summaryrefslogtreecommitdiff
path: root/server/dcc.c
blob: 86507c014e7bfd7a9ce49aea60b1e99ec5af3b81 (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
/* -*- Mode: C; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
   Copyright (C) 2009-2015 Red Hat, Inc.

   This library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Lesser General Public
   License as published by the Free Software Foundation; either
   version 2.1 of the License, or (at your option) any later version.

   This library is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   Lesser General Public License for more details.

   You should have received a copy of the GNU Lesser General Public
   License along with this library; if not, see <http://www.gnu.org/licenses/>.
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include "dcc-private.h"
#include "display-channel.h"
#include "display-channel-private.h"
#include "red-channel-client-private.h"
#include "red-client.h"
#include "main-channel-client.h"
#include "spice-server-enums.h"

G_DEFINE_TYPE(DisplayChannelClient, display_channel_client, RED_TYPE_CHANNEL_CLIENT)

#define DISPLAY_CLIENT_SHORT_TIMEOUT 15000000000ULL //nano
#define DISPLAY_FREE_LIST_DEFAULT_SIZE 128

enum
{
    PROP0,
    PROP_IMAGE_COMPRESSION,
    PROP_JPEG_STATE,
    PROP_ZLIB_GLZ_STATE
};

static void
display_channel_client_get_property(GObject *object,
                                    guint property_id,
                                    GValue *value,
                                    GParamSpec *pspec)
{
    DisplayChannelClient *self = DISPLAY_CHANNEL_CLIENT(object);

    switch (property_id)
    {
        case PROP_IMAGE_COMPRESSION:
             g_value_set_enum(value, self->priv->image_compression);
            break;
        case PROP_JPEG_STATE:
             g_value_set_enum(value, self->priv->jpeg_state);
            break;
        case PROP_ZLIB_GLZ_STATE:
             g_value_set_enum(value, self->priv->zlib_glz_state);
            break;
        default:
            G_OBJECT_WARN_INVALID_PROPERTY_ID(object, property_id, pspec);
    }
}

static void
display_channel_client_set_property(GObject *object,
                                    guint property_id,
                                    const GValue *value,
                                    GParamSpec *pspec)
{
    DisplayChannelClient *self = DISPLAY_CHANNEL_CLIENT(object);

    switch (property_id)
    {
        case PROP_IMAGE_COMPRESSION:
            self->priv->image_compression = g_value_get_enum(value);
            break;
        case PROP_JPEG_STATE:
            self->priv->jpeg_state = g_value_get_enum(value);
            break;
        case PROP_ZLIB_GLZ_STATE:
            self->priv->zlib_glz_state = g_value_get_enum(value);
            break;
        default:
            G_OBJECT_WARN_INVALID_PROPERTY_ID(object, property_id, pspec);
    }
}

static void dcc_init_stream_agents(DisplayChannelClient *dcc);

static void
display_channel_client_constructed(GObject *object)
{
    DisplayChannelClient *self = DISPLAY_CHANNEL_CLIENT(object);

    G_OBJECT_CLASS(display_channel_client_parent_class)->constructed(object);

    dcc_init_stream_agents(self);

    image_encoders_init(&self->priv->encoders, &DCC_TO_DC(self)->priv->encoder_shared_data);
}

static void
display_channel_client_finalize(GObject *object)
{
    DisplayChannelClient *self = DISPLAY_CHANNEL_CLIENT(object);
    g_free(self->priv);

    G_OBJECT_CLASS(display_channel_client_parent_class)->finalize(object);
}

static void
display_channel_client_class_init(DisplayChannelClientClass *klass)
{
    GObjectClass *object_class = G_OBJECT_CLASS(klass);

    object_class->get_property = display_channel_client_get_property;
    object_class->set_property = display_channel_client_set_property;
    object_class->constructed = display_channel_client_constructed;
    object_class->finalize = display_channel_client_finalize;

    g_object_class_install_property(object_class,
                                    PROP_IMAGE_COMPRESSION,
                                    g_param_spec_enum("image-compression",
                                                      "image compression",
                                                      "Image compression type",
                                                      SPICE_TYPE_SPICE_IMAGE_COMPRESSION_T,
                                                      SPICE_IMAGE_COMPRESSION_INVALID,
                                                      G_PARAM_CONSTRUCT | G_PARAM_READWRITE |
                                                      G_PARAM_STATIC_STRINGS));

    g_object_class_install_property(object_class,
                                    PROP_JPEG_STATE,
                                    g_param_spec_enum("jpeg-state",
                                                      "jpeg state",
                                                      "JPEG compression state",
                                                      SPICE_TYPE_SPICE_WAN_COMPRESSION_T,
                                                      SPICE_WAN_COMPRESSION_INVALID,
                                                      G_PARAM_CONSTRUCT | G_PARAM_READWRITE |
                                                      G_PARAM_STATIC_STRINGS));

    g_object_class_install_property(object_class,
                                    PROP_ZLIB_GLZ_STATE,
                                    g_param_spec_enum("zlib-glz-state",
                                                      "zlib glz state",
                                                      "zlib glz state",
                                                      SPICE_TYPE_SPICE_WAN_COMPRESSION_T,
                                                      SPICE_WAN_COMPRESSION_INVALID,
                                                      G_PARAM_CONSTRUCT | G_PARAM_READWRITE |
                                                      G_PARAM_STATIC_STRINGS));
}

static void display_channel_client_init(DisplayChannelClient *self)
{
    /* we need to allocate the private data manually here since
     * g_type_class_add_private() doesn't support private structs larger than
     * 64k */
    self->priv = g_new0(DisplayChannelClientPrivate, 1);

    ring_init(&self->priv->palette_cache_lru);
    self->priv->palette_cache_available = CLIENT_PALETTE_CACHE_SIZE;
    // todo: tune quality according to bandwidth
    self->priv->encoders.jpeg_quality = 85;

    self->priv->send_data.free_list.res =
        spice_malloc(sizeof(SpiceResourceList) +
                     DISPLAY_FREE_LIST_DEFAULT_SIZE * sizeof(SpiceResourceID));
    self->priv->send_data.free_list.res_size = DISPLAY_FREE_LIST_DEFAULT_SIZE;
}

static RedSurfaceCreateItem *red_surface_create_item_new(RedChannel* channel,
                                                         uint32_t surface_id,
                                                         uint32_t width,
                                                         uint32_t height,
                                                         uint32_t format,
                                                         uint32_t flags)
{
    RedSurfaceCreateItem *create;

    create = spice_new(RedSurfaceCreateItem, 1);

    create->surface_create.surface_id = surface_id;
    create->surface_create.width = width;
    create->surface_create.height = height;
    create->surface_create.flags = flags;
    create->surface_create.format = format;

    red_pipe_item_init(&create->pipe_item, RED_PIPE_ITEM_TYPE_CREATE_SURFACE);
    return create;
}

int dcc_drawable_is_in_pipe(DisplayChannelClient *dcc, Drawable *drawable)
{
    RedDrawablePipeItem *dpi;
    GList *l;

    for (l = drawable->pipes; l != NULL; l = l->next) {
        dpi = l->data;
        if (dpi->dcc == dcc) {
            return TRUE;
        }
    }

    return FALSE;
}

/*
 * Return: TRUE if wait_if_used == FALSE, or otherwise, if all of the pipe items that
 * are related to the surface have been cleared (or sent) from the pipe.
 */
int dcc_clear_surface_drawables_from_pipe(DisplayChannelClient *dcc, int surface_id,
                                          int wait_if_used)
{
    GList *l;
    int x;
    RedChannelClient *rcc;

    spice_return_val_if_fail(dcc != NULL, TRUE);
    /* removing the newest drawables that their destination is surface_id and
       no other drawable depends on them */

    rcc = RED_CHANNEL_CLIENT(dcc);
    for (l = rcc->priv->pipe.head; l != NULL; ) {
        Drawable *drawable;
        RedDrawablePipeItem *dpi = NULL;
        int depend_found = FALSE;
        RedPipeItem *item = l->data;
        GList *item_pos = l;

        l = l->next;
        if (item->type == RED_PIPE_ITEM_TYPE_DRAW) {
            dpi = SPICE_CONTAINEROF(item, RedDrawablePipeItem, dpi_pipe_item);
            drawable = dpi->drawable;
        } else if (item->type == RED_PIPE_ITEM_TYPE_UPGRADE) {
            drawable = SPICE_UPCAST(RedUpgradeItem, item)->drawable;
        } else {
            continue;
        }

        if (drawable->surface_id == surface_id) {
            red_channel_client_pipe_remove_and_release_pos(rcc, item_pos);
            continue;
        }

        for (x = 0; x < 3; ++x) {
            if (drawable->surface_deps[x] == surface_id) {
                depend_found = TRUE;
                break;
            }
        }

        if (depend_found) {
            spice_debug("surface %d dependent item found %p, %p", surface_id, drawable, item);
            if (!wait_if_used) {
                return TRUE;
            }
            return red_channel_client_wait_pipe_item_sent(rcc, item_pos,
                                                          COMMON_CLIENT_TIMEOUT);
        }
    }

    if (!wait_if_used) {
        return TRUE;
    }

    /*
     * in case that the pipe didn't contain any item that is dependent on the surface, but
     * there is one during sending. Use a shorter timeout, since it is just one item
     */
    return red_channel_client_wait_outgoing_item(rcc, DISPLAY_CLIENT_SHORT_TIMEOUT);
}

void dcc_create_surface(DisplayChannelClient *dcc, int surface_id)
{
    DisplayChannel *display;
    RedSurface *surface;
    RedSurfaceCreateItem *create;
    uint32_t flags;

    if (!dcc) {
        return;
    }

    display = DCC_TO_DC(dcc);
    flags = is_primary_surface(DCC_TO_DC(dcc), surface_id) ? SPICE_SURFACE_FLAGS_PRIMARY : 0;

    /* don't send redundant create surface commands to client */
    if (!dcc ||
        common_graphics_channel_get_during_target_migrate(COMMON_GRAPHICS_CHANNEL(display)) ||
        dcc->priv->surface_client_created[surface_id]) {
        return;
    }
    surface = &display->priv->surfaces[surface_id];
    create = red_surface_create_item_new(RED_CHANNEL(display),
                                         surface_id, surface->context.width,
                                         surface->context.height,
                                         surface->context.format, flags);
    dcc->priv->surface_client_created[surface_id] = TRUE;
    red_channel_client_pipe_add(RED_CHANNEL_CLIENT(dcc), &create->pipe_item);
}

// adding the pipe item after pos. If pos == NULL, adding to head.
RedImageItem *dcc_add_surface_area_image(DisplayChannelClient *dcc,
                                         int surface_id,
                                         SpiceRect *area,
                                         GList *pipe_item_pos,
                                         int can_lossy)
{
    DisplayChannel *display = DCC_TO_DC(dcc);
    RedSurface *surface = &display->priv->surfaces[surface_id];
    SpiceCanvas *canvas = surface->context.canvas;
    RedImageItem *item;
    int stride;
    int width;
    int height;
    int bpp;
    int all_set;

    spice_assert(area);

    width = area->right - area->left;
    height = area->bottom - area->top;
    bpp = SPICE_SURFACE_FMT_DEPTH(surface->context.format) / 8;
    stride = width * bpp;

    item = (RedImageItem *)spice_malloc_n_m(height, stride, sizeof(RedImageItem));

    red_pipe_item_init(&item->base, RED_PIPE_ITEM_TYPE_IMAGE);

    item->surface_id = surface_id;
    item->image_format =
        spice_bitmap_from_surface_type(surface->context.format);
    item->image_flags = 0;
    item->pos.x = area->left;
    item->pos.y = area->top;
    item->width = width;
    item->height = height;
    item->stride = stride;
    item->top_down = surface->context.top_down;
    item->can_lossy = can_lossy;

    canvas->ops->read_bits(canvas, item->data, stride, area);

    /* For 32bit non-primary surfaces we need to keep any non-zero
       high bytes as the surface may be used as source to an alpha_blend */
    if (!is_primary_surface(display, surface_id) &&
        item->image_format == SPICE_BITMAP_FMT_32BIT &&
        rgb32_data_has_alpha(item->width, item->height, item->stride, item->data, &all_set)) {
        if (all_set) {
            item->image_flags |= SPICE_IMAGE_FLAGS_HIGH_BITS_SET;
        } else {
            item->image_format = SPICE_BITMAP_FMT_RGBA;
        }
    }

    if (pipe_item_pos) {
        red_channel_client_pipe_add_after_pos(RED_CHANNEL_CLIENT(dcc), &item->base, pipe_item_pos);
    } else {
        red_channel_client_pipe_add(RED_CHANNEL_CLIENT(dcc), &item->base);
    }

    return item;
}

void dcc_push_surface_image(DisplayChannelClient *dcc, int surface_id)
{
    DisplayChannel *display;
    SpiceRect area;
    RedSurface *surface;

    if (!dcc) {
        return;
    }

    display = DCC_TO_DC(dcc);
    surface = &display->priv->surfaces[surface_id];
    if (!surface->context.canvas) {
        return;
    }
    area.top = area.left = 0;
    area.right = surface->context.width;
    area.bottom = surface->context.height;

    /* not allowing lossy compression because probably, especially if it is a primary surface,
       it combines both "picture-like" areas with areas that are more "artificial"*/
    dcc_add_surface_area_image(dcc, surface_id, &area, NULL, FALSE);
    red_channel_client_push(RED_CHANNEL_CLIENT(dcc));
}

static void add_drawable_surface_images(DisplayChannelClient *dcc, Drawable *drawable)
{
    DisplayChannel *display = DCC_TO_DC(dcc);
    int x;

    for (x = 0; x < 3; ++x) {
        int surface_id;

        surface_id = drawable->surface_deps[x];
        if (surface_id != -1) {
            if (dcc->priv->surface_client_created[surface_id] == TRUE) {
                continue;
            }
            dcc_create_surface(dcc, surface_id);
            display_channel_current_flush(display, surface_id);
            dcc_push_surface_image(dcc, surface_id);
        }
    }

    if (dcc->priv->surface_client_created[drawable->surface_id] == TRUE) {
        return;
    }

    dcc_create_surface(dcc, drawable->surface_id);
    display_channel_current_flush(display, drawable->surface_id);
    dcc_push_surface_image(dcc, drawable->surface_id);
}

static void red_drawable_pipe_item_free(RedPipeItem *item)
{
    RedDrawablePipeItem *dpi = SPICE_CONTAINEROF(item, RedDrawablePipeItem,
                                                 dpi_pipe_item);
    spice_assert(item->refcount == 0);

    dpi->drawable->pipes = g_list_remove(dpi->drawable->pipes, dpi);
    drawable_unref(dpi->drawable);
    free(dpi);
}

static RedDrawablePipeItem *red_drawable_pipe_item_new(DisplayChannelClient *dcc,
                                                       Drawable *drawable)
{
    RedDrawablePipeItem *dpi;

    dpi = spice_malloc0(sizeof(*dpi));
    dpi->drawable = drawable;
    dpi->dcc = dcc;
    drawable->pipes = g_list_prepend(drawable->pipes, dpi);
    red_pipe_item_init_full(&dpi->dpi_pipe_item, RED_PIPE_ITEM_TYPE_DRAW,
                            red_drawable_pipe_item_free);
    drawable->refs++;
    return dpi;
}

void dcc_prepend_drawable(DisplayChannelClient *dcc, Drawable *drawable)
{
    RedDrawablePipeItem *dpi = red_drawable_pipe_item_new(dcc, drawable);

    add_drawable_surface_images(dcc, drawable);
    red_channel_client_pipe_add(RED_CHANNEL_CLIENT(dcc), &dpi->dpi_pipe_item);
}

void dcc_append_drawable(DisplayChannelClient *dcc, Drawable *drawable)
{
    RedDrawablePipeItem *dpi = red_drawable_pipe_item_new(dcc, drawable);

    add_drawable_surface_images(dcc, drawable);
    red_channel_client_pipe_add_tail_and_push(RED_CHANNEL_CLIENT(dcc), &dpi->dpi_pipe_item);
}

void dcc_add_drawable_after(DisplayChannelClient *dcc, Drawable *drawable, RedPipeItem *pos)
{
    RedDrawablePipeItem *dpi = red_drawable_pipe_item_new(dcc, drawable);

    add_drawable_surface_images(dcc, drawable);
    red_channel_client_pipe_add_after(RED_CHANNEL_CLIENT(dcc), &dpi->dpi_pipe_item, pos);
}

static void dcc_init_stream_agents(DisplayChannelClient *dcc)
{
    int i;
    DisplayChannel *display = DCC_TO_DC(dcc);

    for (i = 0; i < NUM_STREAMS; i++) {
        StreamAgent *agent = &dcc->priv->stream_agents[i];
        agent->stream = &display->priv->streams_buf[i];
        region_init(&agent->vis_region);
        region_init(&agent->clip);
    }
    dcc->priv->use_video_encoder_rate_control =
        red_channel_client_test_remote_cap(RED_CHANNEL_CLIENT(dcc), SPICE_DISPLAY_CAP_STREAM_REPORT);
}

DisplayChannelClient *dcc_new(DisplayChannel *display,
                              RedClient *client, RedsStream *stream,
                              int mig_target,
                              uint32_t *common_caps, int num_common_caps,
                              uint32_t *caps, int num_caps,
                              SpiceImageCompression image_compression,
                              spice_wan_compression_t jpeg_state,
                              spice_wan_compression_t zlib_glz_state)

{
    DisplayChannelClient *dcc;
    GArray *common_caps_array = NULL, *caps_array = NULL;

    if (common_caps) {
        common_caps_array = g_array_sized_new(FALSE, FALSE, sizeof (*common_caps),
                                              num_common_caps);
        g_array_append_vals(common_caps_array, common_caps, num_common_caps);
    }
    if (caps) {
        caps_array = g_array_sized_new(FALSE, FALSE, sizeof (*caps), num_caps);
        g_array_append_vals(caps_array, caps, num_caps);
    }

    dcc = g_initable_new(TYPE_DISPLAY_CHANNEL_CLIENT,
                         NULL, NULL,
                         "channel", display,
                         "client", client,
                         "stream", stream,
                         "monitor-latency", TRUE,
                         "common-caps", common_caps_array,
                         "caps", caps_array,
                         "image-compression", image_compression,
                         "jpeg-state", jpeg_state,
                         "zlib-glz-state", zlib_glz_state,
                         NULL);
    spice_info("New display (client %p) dcc %p stream %p", client, dcc, stream);
    common_graphics_channel_set_during_target_migrate(COMMON_GRAPHICS_CHANNEL(display), mig_target);
    dcc->priv->id = common_graphics_channel_get_qxl(COMMON_GRAPHICS_CHANNEL(display))->id;

    if (common_caps_array)
        g_array_unref(common_caps_array);
    if (caps_array)
        g_array_unref(caps_array);

    return dcc;
}

static void dcc_create_all_streams(DisplayChannelClient *dcc)
{
    Ring *ring = &DCC_TO_DC(dcc)->priv->streams;
    RingItem *item = ring;

    while ((item = ring_next(ring, item))) {
        Stream *stream = SPICE_CONTAINEROF(item, Stream, link);
        dcc_create_stream(dcc, stream);
    }
}

/* TODO: this function is evil^Wsynchronous, fix */
static int display_channel_client_wait_for_init(DisplayChannelClient *dcc)
{
    dcc->priv->expect_init = TRUE;
    uint64_t end_time = spice_get_monotonic_time_ns() + COMMON_CLIENT_TIMEOUT;
    for (;;) {
        red_channel_client_receive(RED_CHANNEL_CLIENT(dcc));
        if (!red_channel_client_is_connected(RED_CHANNEL_CLIENT(dcc))) {
            break;
        }
        if (dcc->priv->pixmap_cache && dcc->priv->encoders.glz_dict) {
            dcc->priv->pixmap_cache_generation = dcc->priv->pixmap_cache->generation;
            /* TODO: move common.id? if it's used for a per client structure.. */
            spice_info("creating encoder with id == %d", dcc->priv->id);
            if (!image_encoders_glz_create(&dcc->priv->encoders, dcc->priv->id)) {
                spice_critical("create global lz failed");
            }
            return TRUE;
        }
        if (spice_get_monotonic_time_ns() > end_time) {
            spice_warning("timeout");
            red_channel_client_disconnect(RED_CHANNEL_CLIENT(dcc));
            break;
        }
        usleep(DISPLAY_CLIENT_RETRY_INTERVAL);
    }
    return FALSE;
}

void dcc_start(DisplayChannelClient *dcc)
{
    DisplayChannel *display = DCC_TO_DC(dcc);
    RedChannelClient *rcc = RED_CHANNEL_CLIENT(dcc);

    red_channel_client_push_set_ack(RED_CHANNEL_CLIENT(dcc));

    if (red_channel_client_is_waiting_for_migrate_data(rcc))
        return;

    if (!display_channel_client_wait_for_init(dcc))
        return;

    red_channel_client_ack_zero_messages_window(RED_CHANNEL_CLIENT(dcc));
    if (display->priv->surfaces[0].context.canvas) {
        display_channel_current_flush(display, 0);
        red_channel_client_pipe_add_type(rcc, RED_PIPE_ITEM_TYPE_INVAL_PALETTE_CACHE);
        dcc_create_surface(dcc, 0);
        dcc_push_surface_image(dcc, 0);
        dcc_push_monitors_config(dcc);
        red_pipe_add_verb(rcc, SPICE_MSG_DISPLAY_MARK);
        dcc_create_all_streams(dcc);
    }

    if (reds_stream_is_plain_unix(red_channel_client_get_stream(rcc)) &&
        red_channel_client_test_remote_cap(rcc, SPICE_DISPLAY_CAP_GL_SCANOUT)) {
        red_channel_client_pipe_add(rcc, dcc_gl_scanout_item_new(rcc, NULL, 0));
        dcc_push_monitors_config(dcc);
    }
}

static void dcc_destroy_stream_agents(DisplayChannelClient *dcc)
{
    int i;

    for (i = 0; i < NUM_STREAMS; i++) {
        StreamAgent *agent = &dcc->priv->stream_agents[i];
        region_destroy(&agent->vis_region);
        region_destroy(&agent->clip);
        if (agent->video_encoder) {
            agent->video_encoder->destroy(agent->video_encoder);
            agent->video_encoder = NULL;
        }
    }
}

void dcc_stop(DisplayChannelClient *dcc)
{
    DisplayChannel *dc = DCC_TO_DC(dcc);

    pixmap_cache_unref(dcc->priv->pixmap_cache);
    dcc->priv->pixmap_cache = NULL;
    dcc_palette_cache_reset(dcc);
    free(dcc->priv->send_data.free_list.res);
    dcc_destroy_stream_agents(dcc);
    image_encoders_free(&dcc->priv->encoders);

    if (dcc->priv->gl_draw_ongoing) {
        display_channel_gl_draw_done(dc);
    }
}

void dcc_stream_agent_clip(DisplayChannelClient* dcc, StreamAgent *agent)
{
    RedStreamClipItem *item = red_stream_clip_item_new(agent);
    int n_rects;

    item->clip_type = SPICE_CLIP_TYPE_RECTS;

    n_rects = pixman_region32_n_rects(&agent->clip);
    item->rects = spice_malloc_n_m(n_rects, sizeof(SpiceRect), sizeof(SpiceClipRects));
    item->rects->num_rects = n_rects;
    region_ret_rects(&agent->clip, item->rects->rects, n_rects);

    red_channel_client_pipe_add(RED_CHANNEL_CLIENT(dcc), &item->base);
}

static void red_monitors_config_item_free(RedPipeItem *base)
{
    RedMonitorsConfigItem *item = SPICE_CONTAINEROF(base, RedMonitorsConfigItem, pipe_item);

    monitors_config_unref(item->monitors_config);
    free(item);
}

static RedMonitorsConfigItem *red_monitors_config_item_new(RedChannel* channel,
                                                           MonitorsConfig *monitors_config)
{
    RedMonitorsConfigItem *mci;

    mci = spice_new(RedMonitorsConfigItem, 1);
    mci->monitors_config = monitors_config_ref(monitors_config);

    red_pipe_item_init_full(&mci->pipe_item, RED_PIPE_ITEM_TYPE_MONITORS_CONFIG,
                            red_monitors_config_item_free);
    return mci;
}

void dcc_push_monitors_config(DisplayChannelClient *dcc)
{
    DisplayChannel *dc = DCC_TO_DC(dcc);
    MonitorsConfig *monitors_config = dc->priv->monitors_config;
    RedMonitorsConfigItem *mci;

    if (monitors_config == NULL) {
        spice_warning("monitors_config is NULL");
        return;
    }

    if (!red_channel_client_test_remote_cap(RED_CHANNEL_CLIENT(dcc),
                                            SPICE_DISPLAY_CAP_MONITORS_CONFIG)) {
        return;
    }

    mci = red_monitors_config_item_new(red_channel_client_get_channel(RED_CHANNEL_CLIENT(dcc)),
                                       monitors_config);
    red_channel_client_pipe_add(RED_CHANNEL_CLIENT(dcc), &mci->pipe_item);
    red_channel_client_push(RED_CHANNEL_CLIENT(dcc));
}

static RedSurfaceDestroyItem *red_surface_destroy_item_new(RedChannel *channel,
                                                           uint32_t surface_id)
{
    RedSurfaceDestroyItem *destroy;

    destroy = spice_new(RedSurfaceDestroyItem, 1);
    destroy->surface_destroy.surface_id = surface_id;
    red_pipe_item_init(&destroy->pipe_item, RED_PIPE_ITEM_TYPE_DESTROY_SURFACE);

    return destroy;
}

RedPipeItem *dcc_gl_scanout_item_new(RedChannelClient *rcc, void *data, int num)
{
    RedGlScanoutUnixItem *item;

    /* FIXME: on !unix peer, start streaming with a video codec */
    if (!reds_stream_is_plain_unix(red_channel_client_get_stream(rcc)) ||
        !red_channel_client_test_remote_cap(rcc, SPICE_DISPLAY_CAP_GL_SCANOUT)) {
        spice_printerr("FIXME: client does not support GL scanout");
        red_channel_client_disconnect(rcc);
        return NULL;
    }

    item = spice_new(RedGlScanoutUnixItem, 1);
    red_pipe_item_init(&item->base, RED_PIPE_ITEM_TYPE_GL_SCANOUT);

    return &item->base;
}

RedPipeItem *dcc_gl_draw_item_new(RedChannelClient *rcc, void *data, int num)
{
    DisplayChannelClient *dcc = DISPLAY_CHANNEL_CLIENT(rcc);
    const SpiceMsgDisplayGlDraw *draw = data;
    RedGlDrawItem *item;

    if (!reds_stream_is_plain_unix(red_channel_client_get_stream(rcc)) ||
        !red_channel_client_test_remote_cap(rcc, SPICE_DISPLAY_CAP_GL_SCANOUT)) {
        spice_printerr("FIXME: client does not support GL scanout");
        red_channel_client_disconnect(rcc);
        return NULL;
    }

    dcc->priv->gl_draw_ongoing = TRUE;
    item = spice_new(RedGlDrawItem, 1);
    item->draw = *draw;
    red_pipe_item_init(&item->base, RED_PIPE_ITEM_TYPE_GL_DRAW);

    return &item->base;
}

void dcc_destroy_surface(DisplayChannelClient *dcc, uint32_t surface_id)
{
    DisplayChannel *display;
    RedChannel *channel;
    RedSurfaceDestroyItem *destroy;

    if (!dcc) {
        return;
    }

    display = DCC_TO_DC(dcc);
    channel = RED_CHANNEL(display);

    if (common_graphics_channel_get_during_target_migrate(COMMON_GRAPHICS_CHANNEL(display)) ||
        !dcc->priv->surface_client_created[surface_id]) {
        return;
    }

    dcc->priv->surface_client_created[surface_id] = FALSE;
    destroy = red_surface_destroy_item_new(channel, surface_id);
    red_channel_client_pipe_add(RED_CHANNEL_CLIENT(dcc), &destroy->pipe_item);
}

#define MIN_DIMENSION_TO_QUIC 3
/**
 * quic doesn't handle:
 *       (1) palette
 */
static bool can_quic_compress(SpiceBitmap *bitmap)
{
    return !bitmap_fmt_is_plt(bitmap->format) &&
            bitmap->x >= MIN_DIMENSION_TO_QUIC && bitmap->y >= MIN_DIMENSION_TO_QUIC;
}
/**
 * lz doesn't handle:
 *       (1) bitmaps with strides that are larger than the width of the image in bytes
 *       (2) unstable bitmaps
 */
static bool can_lz_compress(SpiceBitmap *bitmap)
{
    return !bitmap_has_extra_stride(bitmap) &&
           !(bitmap->data->flags & SPICE_CHUNKS_FLAGS_UNSTABLE);
}

#define MIN_SIZE_TO_COMPRESS 54
static SpiceImageCompression get_compression_for_bitmap(SpiceBitmap *bitmap,
                                                        SpiceImageCompression preferred_compression,
                                                        Drawable *drawable)
{
    if (bitmap->y * bitmap->stride < MIN_SIZE_TO_COMPRESS) { // TODO: change the size cond
        return SPICE_IMAGE_COMPRESSION_OFF;
    }
    if (preferred_compression == SPICE_IMAGE_COMPRESSION_OFF) {
        return SPICE_IMAGE_COMPRESSION_OFF;
    }
    if (preferred_compression == SPICE_IMAGE_COMPRESSION_QUIC) {
        if (can_quic_compress(bitmap)) {
            return SPICE_IMAGE_COMPRESSION_QUIC;
        }
        return SPICE_IMAGE_COMPRESSION_OFF;
    }

    if (preferred_compression == SPICE_IMAGE_COMPRESSION_AUTO_GLZ ||
        preferred_compression == SPICE_IMAGE_COMPRESSION_AUTO_LZ) {
        if (can_quic_compress(bitmap)) {
            if (drawable == NULL ||
                drawable->copy_bitmap_graduality == BITMAP_GRADUAL_INVALID) {
                if (bitmap_fmt_has_graduality(bitmap->format) &&
                    bitmap_get_graduality_level(bitmap) == BITMAP_GRADUAL_HIGH) {
                    return SPICE_IMAGE_COMPRESSION_QUIC;
                }
            } else if (!can_lz_compress(bitmap) ||
                       drawable->copy_bitmap_graduality == BITMAP_GRADUAL_HIGH) {
                return SPICE_IMAGE_COMPRESSION_QUIC;
            }
        }
        if (preferred_compression == SPICE_IMAGE_COMPRESSION_AUTO_LZ) {
            preferred_compression = SPICE_IMAGE_COMPRESSION_LZ;
        } else {
            preferred_compression = SPICE_IMAGE_COMPRESSION_GLZ;
        }
    }

    if (preferred_compression == SPICE_IMAGE_COMPRESSION_GLZ) {
        if (drawable == NULL || !bitmap_fmt_has_graduality(bitmap->format)) {
            preferred_compression = SPICE_IMAGE_COMPRESSION_LZ;
        }
    }

    if (preferred_compression == SPICE_IMAGE_COMPRESSION_LZ4) {
        if (!bitmap_fmt_is_rgb(bitmap->format)) {
            preferred_compression = SPICE_IMAGE_COMPRESSION_LZ;
        }
    }

    if (preferred_compression == SPICE_IMAGE_COMPRESSION_LZ ||
        preferred_compression == SPICE_IMAGE_COMPRESSION_LZ4 ||
        preferred_compression == SPICE_IMAGE_COMPRESSION_GLZ) {
        if (can_lz_compress(bitmap)) {
            return preferred_compression;
        }
        return SPICE_IMAGE_COMPRESSION_OFF;
    }

    return SPICE_IMAGE_COMPRESSION_INVALID;
}

int dcc_compress_image(DisplayChannelClient *dcc,
                       SpiceImage *dest, SpiceBitmap *src, Drawable *drawable,
                       int can_lossy,
                       compress_send_data_t* o_comp_data)
{
    DisplayChannel *display_channel = DCC_TO_DC(dcc);
    SpiceImageCompression image_compression;
    stat_start_time_t start_time;
    int success = FALSE;

    stat_start_time_init(&start_time, &display_channel->priv->encoder_shared_data.off_stat);

    image_compression = get_compression_for_bitmap(src, dcc->priv->image_compression, drawable);
    switch (image_compression) {
    case SPICE_IMAGE_COMPRESSION_OFF:
        break;
    case SPICE_IMAGE_COMPRESSION_QUIC:
        if (can_lossy && display_channel->priv->enable_jpeg &&
            (src->format != SPICE_BITMAP_FMT_RGBA || !bitmap_has_extra_stride(src))) {
            success = image_encoders_compress_jpeg(&dcc->priv->encoders, dest, src, o_comp_data);
            break;
        }
        success = image_encoders_compress_quic(&dcc->priv->encoders, dest, src, o_comp_data);
        break;
    case SPICE_IMAGE_COMPRESSION_GLZ:
        success = image_encoders_compress_glz(&dcc->priv->encoders, dest, src,
                                              drawable->red_drawable, &drawable->glz_retention,
                                              o_comp_data,
                                              display_channel->priv->enable_zlib_glz_wrap);
        if (success) {
            break;
        }
        goto lz_compress;
#ifdef USE_LZ4
    case SPICE_IMAGE_COMPRESSION_LZ4:
        if (red_channel_client_test_remote_cap(RED_CHANNEL_CLIENT(dcc),
                                               SPICE_DISPLAY_CAP_LZ4_COMPRESSION)) {
            success = image_encoders_compress_lz4(&dcc->priv->encoders, dest, src, o_comp_data);
            break;
        }
#endif
lz_compress:
    case SPICE_IMAGE_COMPRESSION_LZ:
        success = image_encoders_compress_lz(&dcc->priv->encoders, dest, src, o_comp_data);
        if (success && !bitmap_fmt_is_rgb(src->format)) {
            dcc_palette_cache_palette(dcc, dest->u.lz_plt.palette, &(dest->u.lz_plt.flags));
        }
        break;
    default:
        spice_error("invalid image compression type %u", image_compression);
    }

    if (!success) {
        uint64_t image_size = src->stride * (uint64_t)src->y;
        stat_compress_add(&display_channel->priv->encoder_shared_data.off_stat, start_time, image_size, image_size);
    }

    return success;
}

#define CLIENT_PALETTE_CACHE
#include "cache-item.tmpl.c"
#undef CLIENT_PALETTE_CACHE

void dcc_palette_cache_palette(DisplayChannelClient *dcc, SpicePalette *palette,
                               uint8_t *flags)
{
    if (palette == NULL) {
        return;
    }
    if (palette->unique) {
        if (red_palette_cache_find(dcc, palette->unique)) {
            *flags |= SPICE_BITMAP_FLAGS_PAL_FROM_CACHE;
            return;
        }
        if (red_palette_cache_add(dcc, palette->unique, 1)) {
            *flags |= SPICE_BITMAP_FLAGS_PAL_CACHE_ME;
        }
    }
}

void dcc_palette_cache_reset(DisplayChannelClient *dcc)
{
    red_palette_cache_reset(dcc, CLIENT_PALETTE_CACHE_SIZE);
}

static void dcc_push_release(DisplayChannelClient *dcc, uint8_t type, uint64_t id,
                             uint64_t* sync_data)
{
    FreeList *free_list = &dcc->priv->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) {
        free_list->res = spice_realloc(free_list->res,
                                       sizeof(*free_list->res) +
                                       free_list->res_size * sizeof(SpiceResourceID) * 2);
        free_list->res_size *= 2;
    }
    free_list->res->resources[free_list->res->count].type = type;
    free_list->res->resources[free_list->res->count++].id = id;
}

int dcc_pixmap_cache_unlocked_add(DisplayChannelClient *dcc, uint64_t id,
                                  uint32_t size, int lossy)
{
    PixmapCache *cache = dcc->priv->pixmap_cache;
    NewCacheItem *item;
    uint64_t serial;
    int key;

    spice_assert(size > 0);

    item = spice_new(NewCacheItem, 1);
    serial = red_channel_client_get_message_serial(RED_CHANNEL_CLIENT(dcc));

    if (cache->generation != dcc->priv->pixmap_cache_generation) {
        if (!dcc->priv->pending_pixmaps_sync) {
            red_channel_client_pipe_add_type(
                                             RED_CHANNEL_CLIENT(dcc), RED_PIPE_ITEM_TYPE_PIXMAP_SYNC);
            dcc->priv->pending_pixmaps_sync = TRUE;
        }
        free(item);
        return FALSE;
    }

    cache->available -= size;
    while (cache->available < 0) {
        NewCacheItem *tail;
        NewCacheItem **now;

        verify(SPICE_OFFSETOF(NewCacheItem, lru_link) == 0);
        if (!(tail = (NewCacheItem *)ring_get_tail(&cache->lru)) ||
                                                   tail->sync[dcc->priv->id] == serial) {
            cache->available += size;
            free(item);
            return FALSE;
        }

        now = &cache->hash_table[BITS_CACHE_HASH_KEY(tail->id)];
        for (;;) {
            spice_assert(*now);
            if (*now == tail) {
                *now = tail->next;
                break;
            }
            now = &(*now)->next;
        }
        ring_remove(&tail->lru_link);
        cache->items--;
        cache->available += tail->size;
        cache->sync[dcc->priv->id] = serial;
        dcc_push_release(dcc, SPICE_RES_TYPE_PIXMAP, tail->id, tail->sync);
        free(tail);
    }
    ++cache->items;
    item->next = cache->hash_table[(key = BITS_CACHE_HASH_KEY(id))];
    cache->hash_table[key] = item;
    ring_item_init(&item->lru_link);
    ring_add(&cache->lru, &item->lru_link);
    item->id = id;
    item->size = size;
    item->lossy = lossy;
    memset(item->sync, 0, sizeof(item->sync));
    item->sync[dcc->priv->id] = serial;
    cache->sync[dcc->priv->id] = serial;
    return TRUE;
}

static int dcc_handle_init(DisplayChannelClient *dcc, SpiceMsgcDisplayInit *init)
{
    gboolean success;
    RedClient *client = red_channel_client_get_client(RED_CHANNEL_CLIENT(dcc));

    spice_return_val_if_fail(dcc->priv->expect_init, FALSE);
    dcc->priv->expect_init = FALSE;

    spice_return_val_if_fail(!dcc->priv->pixmap_cache, FALSE);
    dcc->priv->pixmap_cache = pixmap_cache_get(client,
                                               init->pixmap_cache_id,
                                               init->pixmap_cache_size);
    spice_return_val_if_fail(dcc->priv->pixmap_cache, FALSE);

    success = image_encoders_get_glz_dictionary(&dcc->priv->encoders,
                                                client,
                                                init->glz_dictionary_id,
                                                init->glz_dictionary_window_size);
    spice_return_val_if_fail(success, FALSE);

    return TRUE;
}

static int dcc_handle_stream_report(DisplayChannelClient *dcc,
                                    SpiceMsgcDisplayStreamReport *report)
{
    StreamAgent *agent;

    if (report->stream_id >= NUM_STREAMS) {
        spice_warning("stream_report: invalid stream id %u",
                      report->stream_id);
        return FALSE;
    }

    agent = &dcc->priv->stream_agents[report->stream_id];
    if (!agent->video_encoder) {
        spice_info("stream_report: no encoder for stream id %u. "
                   "The stream has probably been destroyed",
                   report->stream_id);
        return TRUE;
    }

    if (report->unique_id != agent->report_id) {
        spice_warning("stream_report: unique id mismatch: local (%u) != msg (%u) "
                      "The old stream was probably replaced by a new one",
                      agent->report_id, report->unique_id);
        return TRUE;
    }

    agent->video_encoder->client_stream_report(agent->video_encoder,
                                               report->num_frames,
                                               report->num_drops,
                                               report->start_frame_mm_time,
                                               report->end_frame_mm_time,
                                               report->last_frame_delay,
                                               report->audio_delay);
    return TRUE;
}

static int dcc_handle_preferred_compression(DisplayChannelClient *dcc,
        SpiceMsgcDisplayPreferredCompression *pc)
{
    switch (pc->image_compression) {
    case SPICE_IMAGE_COMPRESSION_AUTO_LZ:
    case SPICE_IMAGE_COMPRESSION_AUTO_GLZ:
    case SPICE_IMAGE_COMPRESSION_QUIC:
#ifdef USE_LZ4
    case SPICE_IMAGE_COMPRESSION_LZ4:
#endif
    case SPICE_IMAGE_COMPRESSION_LZ:
    case SPICE_IMAGE_COMPRESSION_GLZ:
    case SPICE_IMAGE_COMPRESSION_OFF:
        dcc->priv->image_compression = pc->image_compression;
        break;
    default:
        spice_warning("preferred-compression: unsupported image compression setting");
    }
    return TRUE;
}

static int dcc_handle_gl_draw_done(DisplayChannelClient *dcc)
{
    DisplayChannel *display = DCC_TO_DC(dcc);

    if (G_UNLIKELY(!dcc->priv->gl_draw_ongoing)) {
        g_warning("unexpected DRAW_DONE received\n");
        /* close client connection */
        return FALSE;
    }

    dcc->priv->gl_draw_ongoing = FALSE;
    display_channel_gl_draw_done(display);

    return TRUE;
}

int dcc_handle_message(RedChannelClient *rcc, uint32_t size, uint16_t type, void *msg)
{
    DisplayChannelClient *dcc = DISPLAY_CHANNEL_CLIENT(rcc);

    switch (type) {
    case SPICE_MSGC_DISPLAY_INIT:
        return dcc_handle_init(dcc, (SpiceMsgcDisplayInit *)msg);
    case SPICE_MSGC_DISPLAY_STREAM_REPORT:
        return dcc_handle_stream_report(dcc, (SpiceMsgcDisplayStreamReport *)msg);
    case SPICE_MSGC_DISPLAY_PREFERRED_COMPRESSION:
        return dcc_handle_preferred_compression(dcc,
            (SpiceMsgcDisplayPreferredCompression *)msg);
    case SPICE_MSGC_DISPLAY_GL_DRAW_DONE:
        return dcc_handle_gl_draw_done(dcc);
    default:
        return red_channel_client_handle_message(rcc, size, type, msg);
    }
}

static int dcc_handle_migrate_glz_dictionary(DisplayChannelClient *dcc,
                                             SpiceMigrateDataDisplay *migrate)
{
    return image_encoders_restore_glz_dictionary(&dcc->priv->encoders,
                                                 red_channel_client_get_client(RED_CHANNEL_CLIENT(dcc)),
                                                 migrate->glz_dict_id,
                                                 &migrate->glz_dict_data);
}

static int restore_surface(DisplayChannelClient *dcc, uint32_t surface_id)
{
    /* we don't process commands till we receive the migration data, thus,
     * we should have not sent any surface to the client. */
    if (dcc->priv->surface_client_created[surface_id]) {
        spice_warning("surface %u is already marked as client_created", surface_id);
        return FALSE;
    }
    dcc->priv->surface_client_created[surface_id] = TRUE;
    return TRUE;
}

static int restore_surfaces_lossless(DisplayChannelClient *dcc,
                                         MigrateDisplaySurfacesAtClientLossless *mig_surfaces)
{
    uint32_t i;

    spice_debug(NULL);
    for (i = 0; i < mig_surfaces->num_surfaces; i++) {
        uint32_t surface_id = mig_surfaces->surfaces[i].id;

        if (!restore_surface(dcc, surface_id))
            return FALSE;
    }
    return TRUE;
}

static int restore_surfaces_lossy(DisplayChannelClient *dcc,
                                  MigrateDisplaySurfacesAtClientLossy *mig_surfaces)
{
    uint32_t i;

    spice_debug(NULL);
    for (i = 0; i < mig_surfaces->num_surfaces; i++) {
        uint32_t surface_id = mig_surfaces->surfaces[i].id;
        SpiceMigrateDataRect *mig_lossy_rect;
        SpiceRect lossy_rect;

        if (!restore_surface(dcc, surface_id))
            return FALSE;

        mig_lossy_rect = &mig_surfaces->surfaces[i].lossy_rect;
        lossy_rect.left = mig_lossy_rect->left;
        lossy_rect.top = mig_lossy_rect->top;
        lossy_rect.right = mig_lossy_rect->right;
        lossy_rect.bottom = mig_lossy_rect->bottom;
        region_init(&dcc->priv->surface_client_lossy_region[surface_id]);
        region_add(&dcc->priv->surface_client_lossy_region[surface_id], &lossy_rect);
    }
    return TRUE;
}

int dcc_handle_migrate_data(DisplayChannelClient *dcc, uint32_t size, void *message)
{
    DisplayChannel *display = DCC_TO_DC(dcc);
    int surfaces_restored = FALSE;
    SpiceMigrateDataHeader *header = (SpiceMigrateDataHeader *)message;
    SpiceMigrateDataDisplay *migrate_data = (SpiceMigrateDataDisplay *)(header + 1);
    uint8_t *surfaces;
    int i;

    spice_return_val_if_fail(
        size >= (sizeof(*migrate_data) + sizeof(SpiceMigrateDataHeader)), FALSE);
    spice_return_val_if_fail(
         migration_protocol_validate_header(header,
             SPICE_MIGRATE_DATA_DISPLAY_MAGIC, SPICE_MIGRATE_DATA_DISPLAY_VERSION), FALSE);

    /* size is set to -1 in order to keep the cache frozen until the original
     * channel client that froze the cache on the src size receives the migrate
     * data and unfreezes the cache by setting its size > 0 and by triggering
     * pixmap_cache_reset */
    dcc->priv->pixmap_cache = pixmap_cache_get(red_channel_client_get_client(RED_CHANNEL_CLIENT(dcc)),
                                               migrate_data->pixmap_cache_id, -1);
    spice_return_val_if_fail(dcc->priv->pixmap_cache, FALSE);

    pthread_mutex_lock(&dcc->priv->pixmap_cache->lock);
    for (i = 0; i < MAX_CACHE_CLIENTS; i++) {
        dcc->priv->pixmap_cache->sync[i] = MAX(dcc->priv->pixmap_cache->sync[i],
                                               migrate_data->pixmap_cache_clients[i]);
    }
    pthread_mutex_unlock(&dcc->priv->pixmap_cache->lock);

    if (migrate_data->pixmap_cache_freezer) {
        /* activating the cache. The cache will start to be active after
         * pixmap_cache_reset is called, when handling RED_PIPE_ITEM_TYPE_PIXMAP_RESET */
        dcc->priv->pixmap_cache->size = migrate_data->pixmap_cache_size;
        red_channel_client_pipe_add_type(RED_CHANNEL_CLIENT(dcc), RED_PIPE_ITEM_TYPE_PIXMAP_RESET);
    }

    if (dcc_handle_migrate_glz_dictionary(dcc, migrate_data)) {
        image_encoders_glz_create(&dcc->priv->encoders, dcc->priv->id);
    } else {
        spice_critical("restoring global lz dictionary failed");
    }

    dcc->is_low_bandwidth = migrate_data->low_bandwidth_setting;

    if (migrate_data->low_bandwidth_setting) {
        red_channel_client_ack_set_client_window(RED_CHANNEL_CLIENT(dcc), WIDE_CLIENT_ACK_WINDOW);
        if (dcc->priv->jpeg_state == SPICE_WAN_COMPRESSION_AUTO) {
            display->priv->enable_jpeg = TRUE;
        }
        if (dcc->priv->zlib_glz_state == SPICE_WAN_COMPRESSION_AUTO) {
            display->priv->enable_zlib_glz_wrap = TRUE;
        }
    }

    surfaces = (uint8_t *)message + migrate_data->surfaces_at_client_ptr;
    surfaces_restored = display->priv->enable_jpeg ?
        restore_surfaces_lossy(dcc, (MigrateDisplaySurfacesAtClientLossy *)surfaces) :
        restore_surfaces_lossless(dcc, (MigrateDisplaySurfacesAtClientLossless*)surfaces);

    spice_return_val_if_fail(surfaces_restored, FALSE);

    red_channel_client_pipe_add_type(RED_CHANNEL_CLIENT(dcc), RED_PIPE_ITEM_TYPE_INVAL_PALETTE_CACHE);
    /* enable sending messages */
    red_channel_client_ack_zero_messages_window(RED_CHANNEL_CLIENT(dcc));
    return TRUE;
}

StreamAgent* dcc_get_stream_agent(DisplayChannelClient *dcc, int stream_id)
{
    return &dcc->priv->stream_agents[stream_id];
}

ImageEncoders* dcc_get_encoders(DisplayChannelClient *dcc)
{
    return &dcc->priv->encoders;
}

spice_wan_compression_t dcc_get_jpeg_state(DisplayChannelClient *dcc)
{
    return dcc->priv->jpeg_state;
}

spice_wan_compression_t dcc_get_zlib_glz_state(DisplayChannelClient *dcc)
{
    return dcc->priv->zlib_glz_state;
}

gboolean dcc_use_video_encoder_rate_control(DisplayChannelClient *dcc)
{
    return dcc->priv->use_video_encoder_rate_control;
}

uint32_t dcc_get_max_stream_latency(DisplayChannelClient *dcc)
{
    return dcc->priv->streams_max_latency;
}

void dcc_set_max_stream_latency(DisplayChannelClient *dcc, uint32_t latency)
{
    dcc->priv->streams_max_latency = latency;
}

uint64_t dcc_get_max_stream_bit_rate(DisplayChannelClient *dcc)
{
    return dcc->priv->streams_max_bit_rate;
}

void dcc_set_max_stream_bit_rate(DisplayChannelClient *dcc, uint64_t rate)
{
    dcc->priv->streams_max_bit_rate = rate;
}

int dcc_config_socket(RedChannelClient *rcc)
{
    RedClient *client = red_channel_client_get_client(rcc);
    MainChannelClient *mcc = red_client_get_main(client);

    DISPLAY_CHANNEL_CLIENT(rcc)->is_low_bandwidth = main_channel_client_is_low_bandwidth(mcc);

    return common_channel_config_socket(rcc);
}

gboolean dcc_is_low_bandwidth(DisplayChannelClient *dcc)
{
    return dcc->is_low_bandwidth;
}