]> Git Repo - qemu.git/blob - ui/vnc-enc-tight.c
vnc: add a non-adaptive option
[qemu.git] / ui / vnc-enc-tight.c
1 /*
2  * QEMU VNC display driver: tight encoding
3  *
4  * From libvncserver/libvncserver/tight.c
5  * Copyright (C) 2000, 2001 Const Kaplinsky.  All Rights Reserved.
6  * Copyright (C) 1999 AT&T Laboratories Cambridge.  All Rights Reserved.
7  *
8  * Copyright (C) 2010 Corentin Chary <[email protected]>
9  *
10  * Permission is hereby granted, free of charge, to any person obtaining a copy
11  * of this software and associated documentation files (the "Software"), to deal
12  * in the Software without restriction, including without limitation the rights
13  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
14  * copies of the Software, and to permit persons to whom the Software is
15  * furnished to do so, subject to the following conditions:
16  *
17  * The above copyright notice and this permission notice shall be included in
18  * all copies or substantial portions of the Software.
19  *
20  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
21  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
22  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
23  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
24  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
25  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
26  * THE SOFTWARE.
27  */
28
29 #include "config-host.h"
30
31 #ifdef CONFIG_VNC_PNG
32 #include <png.h>
33 #endif
34 #ifdef CONFIG_VNC_JPEG
35 #include <stdio.h>
36 #include <jpeglib.h>
37 #endif
38
39 #include "qemu-common.h"
40
41 #include "bswap.h"
42 #include "qint.h"
43 #include "vnc.h"
44 #include "vnc-enc-tight.h"
45 #include "vnc-palette.h"
46
47 /* Compression level stuff. The following array contains various
48    encoder parameters for each of 10 compression levels (0..9).
49    Last three parameters correspond to JPEG quality levels (0..9). */
50
51 static const struct {
52     int max_rect_size, max_rect_width;
53     int mono_min_rect_size, gradient_min_rect_size;
54     int idx_zlib_level, mono_zlib_level, raw_zlib_level, gradient_zlib_level;
55     int gradient_threshold, gradient_threshold24;
56     int idx_max_colors_divisor;
57     int jpeg_quality, jpeg_threshold, jpeg_threshold24;
58 } tight_conf[] = {
59     {   512,   32,   6, 65536, 0, 0, 0, 0,   0,   0,   4,  5, 10000, 23000 },
60     {  2048,  128,   6, 65536, 1, 1, 1, 0,   0,   0,   8, 10,  8000, 18000 },
61     {  6144,  256,   8, 65536, 3, 3, 2, 0,   0,   0,  24, 15,  6500, 15000 },
62     { 10240, 1024,  12, 65536, 5, 5, 3, 0,   0,   0,  32, 25,  5000, 12000 },
63     { 16384, 2048,  12, 65536, 6, 6, 4, 0,   0,   0,  32, 37,  4000, 10000 },
64     { 32768, 2048,  12,  4096, 7, 7, 5, 4, 150, 380,  32, 50,  3000,  8000 },
65     { 65536, 2048,  16,  4096, 7, 7, 6, 4, 170, 420,  48, 60,  2000,  5000 },
66     { 65536, 2048,  16,  4096, 8, 8, 7, 5, 180, 450,  64, 70,  1000,  2500 },
67     { 65536, 2048,  32,  8192, 9, 9, 8, 6, 190, 475,  64, 75,   500,  1200 },
68     { 65536, 2048,  32,  8192, 9, 9, 9, 6, 200, 500,  96, 80,   200,   500 }
69 };
70
71
72 static int tight_send_framebuffer_update(VncState *vs, int x, int y,
73                                          int w, int h);
74
75 #ifdef CONFIG_VNC_JPEG
76 static const struct {
77     double jpeg_freq_min;       /* Don't send JPEG if the freq is bellow */
78     double jpeg_freq_threshold; /* Always send JPEG if the freq is above */
79     int jpeg_idx;               /* Allow indexed JPEG */
80     int jpeg_full;              /* Allow full color JPEG */
81 } tight_jpeg_conf[] = {
82     { 0,   8,  1, 1 },
83     { 0,   8,  1, 1 },
84     { 0,   8,  1, 1 },
85     { 0,   8,  1, 1 },
86     { 0,   10, 1, 1 },
87     { 0.1, 10, 1, 1 },
88     { 0.2, 10, 1, 1 },
89     { 0.3, 12, 0, 0 },
90     { 0.4, 14, 0, 0 },
91     { 0.5, 16, 0, 0 },
92 };
93 #endif
94
95 #ifdef CONFIG_VNC_PNG
96 static const struct {
97     int png_zlib_level, png_filters;
98 } tight_png_conf[] = {
99     { 0, PNG_NO_FILTERS },
100     { 1, PNG_NO_FILTERS },
101     { 2, PNG_NO_FILTERS },
102     { 3, PNG_NO_FILTERS },
103     { 4, PNG_NO_FILTERS },
104     { 5, PNG_ALL_FILTERS },
105     { 6, PNG_ALL_FILTERS },
106     { 7, PNG_ALL_FILTERS },
107     { 8, PNG_ALL_FILTERS },
108     { 9, PNG_ALL_FILTERS },
109 };
110
111 static int send_png_rect(VncState *vs, int x, int y, int w, int h,
112                          VncPalette *palette);
113
114 static bool tight_can_send_png_rect(VncState *vs, int w, int h)
115 {
116     if (vs->tight.type != VNC_ENCODING_TIGHT_PNG) {
117         return false;
118     }
119
120     if (ds_get_bytes_per_pixel(vs->ds) == 1 ||
121         vs->clientds.pf.bytes_per_pixel == 1) {
122         return false;
123     }
124
125     return true;
126 }
127 #endif
128
129 /*
130  * Code to guess if given rectangle is suitable for smooth image
131  * compression (by applying "gradient" filter or JPEG coder).
132  */
133
134 static unsigned int
135 tight_detect_smooth_image24(VncState *vs, int w, int h)
136 {
137     int off;
138     int x, y, d, dx;
139     unsigned int c;
140     unsigned int stats[256];
141     int pixels = 0;
142     int pix, left[3];
143     unsigned int errors;
144     unsigned char *buf = vs->tight.tight.buffer;
145
146     /*
147      * If client is big-endian, color samples begin from the second
148      * byte (offset 1) of a 32-bit pixel value.
149      */
150     off = !!(vs->clientds.flags & QEMU_BIG_ENDIAN_FLAG);
151
152     memset(stats, 0, sizeof (stats));
153
154     for (y = 0, x = 0; y < h && x < w;) {
155         for (d = 0; d < h - y && d < w - x - VNC_TIGHT_DETECT_SUBROW_WIDTH;
156              d++) {
157             for (c = 0; c < 3; c++) {
158                 left[c] = buf[((y+d)*w+x+d)*4+off+c] & 0xFF;
159             }
160             for (dx = 1; dx <= VNC_TIGHT_DETECT_SUBROW_WIDTH; dx++) {
161                 for (c = 0; c < 3; c++) {
162                     pix = buf[((y+d)*w+x+d+dx)*4+off+c] & 0xFF;
163                     stats[abs(pix - left[c])]++;
164                     left[c] = pix;
165                 }
166                 pixels++;
167             }
168         }
169         if (w > h) {
170             x += h;
171             y = 0;
172         } else {
173             x = 0;
174             y += w;
175         }
176     }
177
178     /* 95% smooth or more ... */
179     if (stats[0] * 33 / pixels >= 95) {
180         return 0;
181     }
182
183     errors = 0;
184     for (c = 1; c < 8; c++) {
185         errors += stats[c] * (c * c);
186         if (stats[c] == 0 || stats[c] > stats[c-1] * 2) {
187             return 0;
188         }
189     }
190     for (; c < 256; c++) {
191         errors += stats[c] * (c * c);
192     }
193     errors /= (pixels * 3 - stats[0]);
194
195     return errors;
196 }
197
198 #define DEFINE_DETECT_FUNCTION(bpp)                                     \
199                                                                         \
200     static unsigned int                                                 \
201     tight_detect_smooth_image##bpp(VncState *vs, int w, int h) {        \
202         bool endian;                                                    \
203         uint##bpp##_t pix;                                              \
204         int max[3], shift[3];                                           \
205         int x, y, d, dx;                                                \
206         unsigned int c;                                                 \
207         unsigned int stats[256];                                        \
208         int pixels = 0;                                                 \
209         int sample, sum, left[3];                                       \
210         unsigned int errors;                                            \
211         unsigned char *buf = vs->tight.tight.buffer;                    \
212                                                                         \
213         endian = ((vs->clientds.flags & QEMU_BIG_ENDIAN_FLAG) !=        \
214                   (vs->ds->surface->flags & QEMU_BIG_ENDIAN_FLAG));     \
215                                                                         \
216                                                                         \
217         max[0] = vs->clientds.pf.rmax;                                  \
218         max[1] = vs->clientds.pf.gmax;                                  \
219         max[2] = vs->clientds.pf.bmax;                                  \
220         shift[0] = vs->clientds.pf.rshift;                              \
221         shift[1] = vs->clientds.pf.gshift;                              \
222         shift[2] = vs->clientds.pf.bshift;                              \
223                                                                         \
224         memset(stats, 0, sizeof(stats));                                \
225                                                                         \
226         y = 0, x = 0;                                                   \
227         while (y < h && x < w) {                                        \
228             for (d = 0; d < h - y &&                                    \
229                      d < w - x - VNC_TIGHT_DETECT_SUBROW_WIDTH; d++) {  \
230                 pix = ((uint##bpp##_t *)buf)[(y+d)*w+x+d];              \
231                 if (endian) {                                           \
232                     pix = bswap##bpp(pix);                              \
233                 }                                                       \
234                 for (c = 0; c < 3; c++) {                               \
235                     left[c] = (int)(pix >> shift[c] & max[c]);          \
236                 }                                                       \
237                 for (dx = 1; dx <= VNC_TIGHT_DETECT_SUBROW_WIDTH;       \
238                      dx++) {                                            \
239                     pix = ((uint##bpp##_t *)buf)[(y+d)*w+x+d+dx];       \
240                     if (endian) {                                       \
241                         pix = bswap##bpp(pix);                          \
242                     }                                                   \
243                     sum = 0;                                            \
244                     for (c = 0; c < 3; c++) {                           \
245                         sample = (int)(pix >> shift[c] & max[c]);       \
246                         sum += abs(sample - left[c]);                   \
247                         left[c] = sample;                               \
248                     }                                                   \
249                     if (sum > 255) {                                    \
250                         sum = 255;                                      \
251                     }                                                   \
252                     stats[sum]++;                                       \
253                     pixels++;                                           \
254                 }                                                       \
255             }                                                           \
256             if (w > h) {                                                \
257                 x += h;                                                 \
258                 y = 0;                                                  \
259             } else {                                                    \
260                 x = 0;                                                  \
261                 y += w;                                                 \
262             }                                                           \
263         }                                                               \
264                                                                         \
265         if ((stats[0] + stats[1]) * 100 / pixels >= 90) {               \
266             return 0;                                                   \
267         }                                                               \
268                                                                         \
269         errors = 0;                                                     \
270         for (c = 1; c < 8; c++) {                                       \
271             errors += stats[c] * (c * c);                               \
272             if (stats[c] == 0 || stats[c] > stats[c-1] * 2) {           \
273                 return 0;                                               \
274             }                                                           \
275         }                                                               \
276         for (; c < 256; c++) {                                          \
277             errors += stats[c] * (c * c);                               \
278         }                                                               \
279         errors /= (pixels - stats[0]);                                  \
280                                                                         \
281         return errors;                                                  \
282     }
283
284 DEFINE_DETECT_FUNCTION(16)
285 DEFINE_DETECT_FUNCTION(32)
286
287 static int
288 tight_detect_smooth_image(VncState *vs, int w, int h)
289 {
290     unsigned int errors;
291     int compression = vs->tight.compression;
292     int quality = vs->tight.quality;
293
294     if (!vs->vd->lossy) {
295         return 0;
296     }
297
298     if (ds_get_bytes_per_pixel(vs->ds) == 1 ||
299         vs->clientds.pf.bytes_per_pixel == 1 ||
300         w < VNC_TIGHT_DETECT_MIN_WIDTH || h < VNC_TIGHT_DETECT_MIN_HEIGHT) {
301         return 0;
302     }
303
304     if (vs->tight.quality != (uint8_t)-1) {
305         if (w * h < VNC_TIGHT_JPEG_MIN_RECT_SIZE) {
306             return 0;
307         }
308     } else {
309         if (w * h < tight_conf[compression].gradient_min_rect_size) {
310             return 0;
311         }
312     }
313
314     if (vs->clientds.pf.bytes_per_pixel == 4) {
315         if (vs->tight.pixel24) {
316             errors = tight_detect_smooth_image24(vs, w, h);
317             if (vs->tight.quality != (uint8_t)-1) {
318                 return (errors < tight_conf[quality].jpeg_threshold24);
319             }
320             return (errors < tight_conf[compression].gradient_threshold24);
321         } else {
322             errors = tight_detect_smooth_image32(vs, w, h);
323         }
324     } else {
325         errors = tight_detect_smooth_image16(vs, w, h);
326     }
327     if (quality != -1) {
328         return (errors < tight_conf[quality].jpeg_threshold);
329     }
330     return (errors < tight_conf[compression].gradient_threshold);
331 }
332
333 /*
334  * Code to determine how many different colors used in rectangle.
335  */
336 #define DEFINE_FILL_PALETTE_FUNCTION(bpp)                               \
337                                                                         \
338     static int                                                          \
339     tight_fill_palette##bpp(VncState *vs, int x, int y,                 \
340                             int max, size_t count,                      \
341                             uint32_t *bg, uint32_t *fg,                 \
342                             VncPalette **palette) {                     \
343         uint##bpp##_t *data;                                            \
344         uint##bpp##_t c0, c1, ci;                                       \
345         int i, n0, n1;                                                  \
346                                                                         \
347         data = (uint##bpp##_t *)vs->tight.tight.buffer;                 \
348                                                                         \
349         c0 = data[0];                                                   \
350         i = 1;                                                          \
351         while (i < count && data[i] == c0)                              \
352             i++;                                                        \
353         if (i >= count) {                                               \
354             *bg = *fg = c0;                                             \
355             return 1;                                                   \
356         }                                                               \
357                                                                         \
358         if (max < 2) {                                                  \
359             return 0;                                                   \
360         }                                                               \
361                                                                         \
362         n0 = i;                                                         \
363         c1 = data[i];                                                   \
364         n1 = 0;                                                         \
365         for (i++; i < count; i++) {                                     \
366             ci = data[i];                                               \
367             if (ci == c0) {                                             \
368                 n0++;                                                   \
369             } else if (ci == c1) {                                      \
370                 n1++;                                                   \
371             } else                                                      \
372                 break;                                                  \
373         }                                                               \
374         if (i >= count) {                                               \
375             if (n0 > n1) {                                              \
376                 *bg = (uint32_t)c0;                                     \
377                 *fg = (uint32_t)c1;                                     \
378             } else {                                                    \
379                 *bg = (uint32_t)c1;                                     \
380                 *fg = (uint32_t)c0;                                     \
381             }                                                           \
382             return 2;                                                   \
383         }                                                               \
384                                                                         \
385         if (max == 2) {                                                 \
386             return 0;                                                   \
387         }                                                               \
388                                                                         \
389         *palette = palette_new(max, bpp);                               \
390         palette_put(*palette, c0);                                      \
391         palette_put(*palette, c1);                                      \
392         palette_put(*palette, ci);                                      \
393                                                                         \
394         for (i++; i < count; i++) {                                     \
395             if (data[i] == ci) {                                        \
396                 continue;                                               \
397             } else {                                                    \
398                 ci = data[i];                                           \
399                 if (!palette_put(*palette, (uint32_t)ci)) {             \
400                     return 0;                                           \
401                 }                                                       \
402             }                                                           \
403         }                                                               \
404                                                                         \
405         return palette_size(*palette);                                  \
406     }
407
408 DEFINE_FILL_PALETTE_FUNCTION(8)
409 DEFINE_FILL_PALETTE_FUNCTION(16)
410 DEFINE_FILL_PALETTE_FUNCTION(32)
411
412 static int tight_fill_palette(VncState *vs, int x, int y,
413                               size_t count, uint32_t *bg, uint32_t *fg,
414                               VncPalette **palette)
415 {
416     int max;
417
418     max = count / tight_conf[vs->tight.compression].idx_max_colors_divisor;
419     if (max < 2 &&
420         count >= tight_conf[vs->tight.compression].mono_min_rect_size) {
421         max = 2;
422     }
423     if (max >= 256) {
424         max = 256;
425     }
426
427     switch(vs->clientds.pf.bytes_per_pixel) {
428     case 4:
429         return tight_fill_palette32(vs, x, y, max, count, bg, fg, palette);
430     case 2:
431         return tight_fill_palette16(vs, x, y, max, count, bg, fg, palette);
432     default:
433         max = 2;
434         return tight_fill_palette8(vs, x, y, max, count, bg, fg, palette);
435     }
436     return 0;
437 }
438
439 /*
440  * Converting truecolor samples into palette indices.
441  */
442 #define DEFINE_IDX_ENCODE_FUNCTION(bpp)                                 \
443                                                                         \
444     static void                                                         \
445     tight_encode_indexed_rect##bpp(uint8_t *buf, int count,             \
446                                    VncPalette *palette) {               \
447         uint##bpp##_t *src;                                             \
448         uint##bpp##_t rgb;                                              \
449         int i, rep;                                                     \
450         uint8_t idx;                                                    \
451                                                                         \
452         src = (uint##bpp##_t *) buf;                                    \
453                                                                         \
454         for (i = 0; i < count; i++) {                                   \
455                                                                         \
456             rgb = *src++;                                               \
457             rep = 0;                                                    \
458             while (i < count && *src == rgb) {                          \
459                 rep++, src++, i++;                                      \
460             }                                                           \
461             idx = palette_idx(palette, rgb);                            \
462             /*                                                          \
463              * Should never happen, but don't break everything          \
464              * if it does, use the first color instead                  \
465              */                                                         \
466             if (idx == (uint8_t)-1) {                                   \
467                 idx = 0;                                                \
468             }                                                           \
469             while (rep >= 0) {                                          \
470                 *buf++ = idx;                                           \
471                 rep--;                                                  \
472             }                                                           \
473         }                                                               \
474     }
475
476 DEFINE_IDX_ENCODE_FUNCTION(16)
477 DEFINE_IDX_ENCODE_FUNCTION(32)
478
479 #define DEFINE_MONO_ENCODE_FUNCTION(bpp)                                \
480                                                                         \
481     static void                                                         \
482     tight_encode_mono_rect##bpp(uint8_t *buf, int w, int h,             \
483                                 uint##bpp##_t bg, uint##bpp##_t fg) {   \
484         uint##bpp##_t *ptr;                                             \
485         unsigned int value, mask;                                       \
486         int aligned_width;                                              \
487         int x, y, bg_bits;                                              \
488                                                                         \
489         ptr = (uint##bpp##_t *) buf;                                    \
490         aligned_width = w - w % 8;                                      \
491                                                                         \
492         for (y = 0; y < h; y++) {                                       \
493             for (x = 0; x < aligned_width; x += 8) {                    \
494                 for (bg_bits = 0; bg_bits < 8; bg_bits++) {             \
495                     if (*ptr++ != bg) {                                 \
496                         break;                                          \
497                     }                                                   \
498                 }                                                       \
499                 if (bg_bits == 8) {                                     \
500                     *buf++ = 0;                                         \
501                     continue;                                           \
502                 }                                                       \
503                 mask = 0x80 >> bg_bits;                                 \
504                 value = mask;                                           \
505                 for (bg_bits++; bg_bits < 8; bg_bits++) {               \
506                     mask >>= 1;                                         \
507                     if (*ptr++ != bg) {                                 \
508                         value |= mask;                                  \
509                     }                                                   \
510                 }                                                       \
511                 *buf++ = (uint8_t)value;                                \
512             }                                                           \
513                                                                         \
514             mask = 0x80;                                                \
515             value = 0;                                                  \
516             if (x >= w) {                                               \
517                 continue;                                               \
518             }                                                           \
519                                                                         \
520             for (; x < w; x++) {                                        \
521                 if (*ptr++ != bg) {                                     \
522                     value |= mask;                                      \
523                 }                                                       \
524                 mask >>= 1;                                             \
525             }                                                           \
526             *buf++ = (uint8_t)value;                                    \
527         }                                                               \
528     }
529
530 DEFINE_MONO_ENCODE_FUNCTION(8)
531 DEFINE_MONO_ENCODE_FUNCTION(16)
532 DEFINE_MONO_ENCODE_FUNCTION(32)
533
534 /*
535  * ``Gradient'' filter for 24-bit color samples.
536  * Should be called only when redMax, greenMax and blueMax are 255.
537  * Color components assumed to be byte-aligned.
538  */
539
540 static void
541 tight_filter_gradient24(VncState *vs, uint8_t *buf, int w, int h)
542 {
543     uint32_t *buf32;
544     uint32_t pix32;
545     int shift[3];
546     int *prev;
547     int here[3], upper[3], left[3], upperleft[3];
548     int prediction;
549     int x, y, c;
550
551     buf32 = (uint32_t *)buf;
552     memset(vs->tight.gradient.buffer, 0, w * 3 * sizeof(int));
553
554     if ((vs->clientds.flags & QEMU_BIG_ENDIAN_FLAG) ==
555         (vs->ds->surface->flags & QEMU_BIG_ENDIAN_FLAG)) {
556         shift[0] = vs->clientds.pf.rshift;
557         shift[1] = vs->clientds.pf.gshift;
558         shift[2] = vs->clientds.pf.bshift;
559     } else {
560         shift[0] = 24 - vs->clientds.pf.rshift;
561         shift[1] = 24 - vs->clientds.pf.gshift;
562         shift[2] = 24 - vs->clientds.pf.bshift;
563     }
564
565     for (y = 0; y < h; y++) {
566         for (c = 0; c < 3; c++) {
567             upper[c] = 0;
568             here[c] = 0;
569         }
570         prev = (int *)vs->tight.gradient.buffer;
571         for (x = 0; x < w; x++) {
572             pix32 = *buf32++;
573             for (c = 0; c < 3; c++) {
574                 upperleft[c] = upper[c];
575                 left[c] = here[c];
576                 upper[c] = *prev;
577                 here[c] = (int)(pix32 >> shift[c] & 0xFF);
578                 *prev++ = here[c];
579
580                 prediction = left[c] + upper[c] - upperleft[c];
581                 if (prediction < 0) {
582                     prediction = 0;
583                 } else if (prediction > 0xFF) {
584                     prediction = 0xFF;
585                 }
586                 *buf++ = (char)(here[c] - prediction);
587             }
588         }
589     }
590 }
591
592
593 /*
594  * ``Gradient'' filter for other color depths.
595  */
596
597 #define DEFINE_GRADIENT_FILTER_FUNCTION(bpp)                            \
598                                                                         \
599     static void                                                         \
600     tight_filter_gradient##bpp(VncState *vs, uint##bpp##_t *buf,        \
601                                int w, int h) {                          \
602         uint##bpp##_t pix, diff;                                        \
603         bool endian;                                                    \
604         int *prev;                                                      \
605         int max[3], shift[3];                                           \
606         int here[3], upper[3], left[3], upperleft[3];                   \
607         int prediction;                                                 \
608         int x, y, c;                                                    \
609                                                                         \
610         memset (vs->tight.gradient.buffer, 0, w * 3 * sizeof(int));     \
611                                                                         \
612         endian = ((vs->clientds.flags & QEMU_BIG_ENDIAN_FLAG) !=        \
613                   (vs->ds->surface->flags & QEMU_BIG_ENDIAN_FLAG));     \
614                                                                         \
615         max[0] = vs->clientds.pf.rmax;                                  \
616         max[1] = vs->clientds.pf.gmax;                                  \
617         max[2] = vs->clientds.pf.bmax;                                  \
618         shift[0] = vs->clientds.pf.rshift;                              \
619         shift[1] = vs->clientds.pf.gshift;                              \
620         shift[2] = vs->clientds.pf.bshift;                              \
621                                                                         \
622         for (y = 0; y < h; y++) {                                       \
623             for (c = 0; c < 3; c++) {                                   \
624                 upper[c] = 0;                                           \
625                 here[c] = 0;                                            \
626             }                                                           \
627             prev = (int *)vs->tight.gradient.buffer;                    \
628             for (x = 0; x < w; x++) {                                   \
629                 pix = *buf;                                             \
630                 if (endian) {                                           \
631                     pix = bswap##bpp(pix);                              \
632                 }                                                       \
633                 diff = 0;                                               \
634                 for (c = 0; c < 3; c++) {                               \
635                     upperleft[c] = upper[c];                            \
636                     left[c] = here[c];                                  \
637                     upper[c] = *prev;                                   \
638                     here[c] = (int)(pix >> shift[c] & max[c]);          \
639                     *prev++ = here[c];                                  \
640                                                                         \
641                     prediction = left[c] + upper[c] - upperleft[c];     \
642                     if (prediction < 0) {                               \
643                         prediction = 0;                                 \
644                     } else if (prediction > max[c]) {                   \
645                         prediction = max[c];                            \
646                     }                                                   \
647                     diff |= ((here[c] - prediction) & max[c])           \
648                         << shift[c];                                    \
649                 }                                                       \
650                 if (endian) {                                           \
651                     diff = bswap##bpp(diff);                            \
652                 }                                                       \
653                 *buf++ = diff;                                          \
654             }                                                           \
655         }                                                               \
656     }
657
658 DEFINE_GRADIENT_FILTER_FUNCTION(16)
659 DEFINE_GRADIENT_FILTER_FUNCTION(32)
660
661 /*
662  * Check if a rectangle is all of the same color. If needSameColor is
663  * set to non-zero, then also check that its color equals to the
664  * *colorPtr value. The result is 1 if the test is successful, and in
665  * that case new color will be stored in *colorPtr.
666  */
667
668 #define DEFINE_CHECK_SOLID_FUNCTION(bpp)                                \
669                                                                         \
670     static bool                                                         \
671     check_solid_tile##bpp(VncState *vs, int x, int y, int w, int h,     \
672                           uint32_t* color, bool samecolor)              \
673     {                                                                   \
674         VncDisplay *vd = vs->vd;                                        \
675         uint##bpp##_t *fbptr;                                           \
676         uint##bpp##_t c;                                                \
677         int dx, dy;                                                     \
678                                                                         \
679         fbptr = (uint##bpp##_t *)                                       \
680             (vd->server->data + y * ds_get_linesize(vs->ds) +           \
681              x * ds_get_bytes_per_pixel(vs->ds));                       \
682                                                                         \
683         c = *fbptr;                                                     \
684         if (samecolor && (uint32_t)c != *color) {                       \
685             return false;                                               \
686         }                                                               \
687                                                                         \
688         for (dy = 0; dy < h; dy++) {                                    \
689             for (dx = 0; dx < w; dx++) {                                \
690                 if (c != fbptr[dx]) {                                   \
691                     return false;                                       \
692                 }                                                       \
693             }                                                           \
694             fbptr = (uint##bpp##_t *)                                   \
695                 ((uint8_t *)fbptr + ds_get_linesize(vs->ds));           \
696         }                                                               \
697                                                                         \
698         *color = (uint32_t)c;                                           \
699         return true;                                                    \
700     }
701
702 DEFINE_CHECK_SOLID_FUNCTION(32)
703 DEFINE_CHECK_SOLID_FUNCTION(16)
704 DEFINE_CHECK_SOLID_FUNCTION(8)
705
706 static bool check_solid_tile(VncState *vs, int x, int y, int w, int h,
707                              uint32_t* color, bool samecolor)
708 {
709     VncDisplay *vd = vs->vd;
710
711     switch(vd->server->pf.bytes_per_pixel) {
712     case 4:
713         return check_solid_tile32(vs, x, y, w, h, color, samecolor);
714     case 2:
715         return check_solid_tile16(vs, x, y, w, h, color, samecolor);
716     default:
717         return check_solid_tile8(vs, x, y, w, h, color, samecolor);
718     }
719 }
720
721 static void find_best_solid_area(VncState *vs, int x, int y, int w, int h,
722                                  uint32_t color, int *w_ptr, int *h_ptr)
723 {
724     int dx, dy, dw, dh;
725     int w_prev;
726     int w_best = 0, h_best = 0;
727
728     w_prev = w;
729
730     for (dy = y; dy < y + h; dy += VNC_TIGHT_MAX_SPLIT_TILE_SIZE) {
731
732         dh = MIN(VNC_TIGHT_MAX_SPLIT_TILE_SIZE, y + h - dy);
733         dw = MIN(VNC_TIGHT_MAX_SPLIT_TILE_SIZE, w_prev);
734
735         if (!check_solid_tile(vs, x, dy, dw, dh, &color, true)) {
736             break;
737         }
738
739         for (dx = x + dw; dx < x + w_prev;) {
740             dw = MIN(VNC_TIGHT_MAX_SPLIT_TILE_SIZE, x + w_prev - dx);
741
742             if (!check_solid_tile(vs, dx, dy, dw, dh, &color, true)) {
743                 break;
744             }
745             dx += dw;
746         }
747
748         w_prev = dx - x;
749         if (w_prev * (dy + dh - y) > w_best * h_best) {
750             w_best = w_prev;
751             h_best = dy + dh - y;
752         }
753     }
754
755     *w_ptr = w_best;
756     *h_ptr = h_best;
757 }
758
759 static void extend_solid_area(VncState *vs, int x, int y, int w, int h,
760                               uint32_t color, int *x_ptr, int *y_ptr,
761                               int *w_ptr, int *h_ptr)
762 {
763     int cx, cy;
764
765     /* Try to extend the area upwards. */
766     for ( cy = *y_ptr - 1;
767           cy >= y && check_solid_tile(vs, *x_ptr, cy, *w_ptr, 1, &color, true);
768           cy-- );
769     *h_ptr += *y_ptr - (cy + 1);
770     *y_ptr = cy + 1;
771
772     /* ... downwards. */
773     for ( cy = *y_ptr + *h_ptr;
774           cy < y + h &&
775               check_solid_tile(vs, *x_ptr, cy, *w_ptr, 1, &color, true);
776           cy++ );
777     *h_ptr += cy - (*y_ptr + *h_ptr);
778
779     /* ... to the left. */
780     for ( cx = *x_ptr - 1;
781           cx >= x && check_solid_tile(vs, cx, *y_ptr, 1, *h_ptr, &color, true);
782           cx-- );
783     *w_ptr += *x_ptr - (cx + 1);
784     *x_ptr = cx + 1;
785
786     /* ... to the right. */
787     for ( cx = *x_ptr + *w_ptr;
788           cx < x + w &&
789               check_solid_tile(vs, cx, *y_ptr, 1, *h_ptr, &color, true);
790           cx++ );
791     *w_ptr += cx - (*x_ptr + *w_ptr);
792 }
793
794 static int tight_init_stream(VncState *vs, int stream_id,
795                              int level, int strategy)
796 {
797     z_streamp zstream = &vs->tight.stream[stream_id];
798
799     if (zstream->opaque == NULL) {
800         int err;
801
802         VNC_DEBUG("VNC: TIGHT: initializing zlib stream %d\n", stream_id);
803         VNC_DEBUG("VNC: TIGHT: opaque = %p | vs = %p\n", zstream->opaque, vs);
804         zstream->zalloc = vnc_zlib_zalloc;
805         zstream->zfree = vnc_zlib_zfree;
806
807         err = deflateInit2(zstream, level, Z_DEFLATED, MAX_WBITS,
808                            MAX_MEM_LEVEL, strategy);
809
810         if (err != Z_OK) {
811             fprintf(stderr, "VNC: error initializing zlib\n");
812             return -1;
813         }
814
815         vs->tight.levels[stream_id] = level;
816         zstream->opaque = vs;
817     }
818
819     if (vs->tight.levels[stream_id] != level) {
820         if (deflateParams(zstream, level, strategy) != Z_OK) {
821             return -1;
822         }
823         vs->tight.levels[stream_id] = level;
824     }
825     return 0;
826 }
827
828 static void tight_send_compact_size(VncState *vs, size_t len)
829 {
830     int lpc = 0;
831     int bytes = 0;
832     char buf[3] = {0, 0, 0};
833
834     buf[bytes++] = len & 0x7F;
835     if (len > 0x7F) {
836         buf[bytes-1] |= 0x80;
837         buf[bytes++] = (len >> 7) & 0x7F;
838         if (len > 0x3FFF) {
839             buf[bytes-1] |= 0x80;
840             buf[bytes++] = (len >> 14) & 0xFF;
841         }
842     }
843     for (lpc = 0; lpc < bytes; lpc++) {
844         vnc_write_u8(vs, buf[lpc]);
845     }
846 }
847
848 static int tight_compress_data(VncState *vs, int stream_id, size_t bytes,
849                                int level, int strategy)
850 {
851     z_streamp zstream = &vs->tight.stream[stream_id];
852     int previous_out;
853
854     if (bytes < VNC_TIGHT_MIN_TO_COMPRESS) {
855         vnc_write(vs, vs->tight.tight.buffer, vs->tight.tight.offset);
856         return bytes;
857     }
858
859     if (tight_init_stream(vs, stream_id, level, strategy)) {
860         return -1;
861     }
862
863     /* reserve memory in output buffer */
864     buffer_reserve(&vs->tight.zlib, bytes + 64);
865
866     /* set pointers */
867     zstream->next_in = vs->tight.tight.buffer;
868     zstream->avail_in = vs->tight.tight.offset;
869     zstream->next_out = vs->tight.zlib.buffer + vs->tight.zlib.offset;
870     zstream->avail_out = vs->tight.zlib.capacity - vs->tight.zlib.offset;
871     zstream->data_type = Z_BINARY;
872     previous_out = zstream->total_out;
873
874     /* start encoding */
875     if (deflate(zstream, Z_SYNC_FLUSH) != Z_OK) {
876         fprintf(stderr, "VNC: error during tight compression\n");
877         return -1;
878     }
879
880     vs->tight.zlib.offset = vs->tight.zlib.capacity - zstream->avail_out;
881     bytes = zstream->total_out - previous_out;
882
883     tight_send_compact_size(vs, bytes);
884     vnc_write(vs, vs->tight.zlib.buffer, bytes);
885
886     buffer_reset(&vs->tight.zlib);
887
888     return bytes;
889 }
890
891 /*
892  * Subencoding implementations.
893  */
894 static void tight_pack24(VncState *vs, uint8_t *buf, size_t count, size_t *ret)
895 {
896     uint32_t *buf32;
897     uint32_t pix;
898     int rshift, gshift, bshift;
899
900     buf32 = (uint32_t *)buf;
901
902     if ((vs->clientds.flags & QEMU_BIG_ENDIAN_FLAG) ==
903         (vs->ds->surface->flags & QEMU_BIG_ENDIAN_FLAG)) {
904         rshift = vs->clientds.pf.rshift;
905         gshift = vs->clientds.pf.gshift;
906         bshift = vs->clientds.pf.bshift;
907     } else {
908         rshift = 24 - vs->clientds.pf.rshift;
909         gshift = 24 - vs->clientds.pf.gshift;
910         bshift = 24 - vs->clientds.pf.bshift;
911     }
912
913     if (ret) {
914         *ret = count * 3;
915     }
916
917     while (count--) {
918         pix = *buf32++;
919         *buf++ = (char)(pix >> rshift);
920         *buf++ = (char)(pix >> gshift);
921         *buf++ = (char)(pix >> bshift);
922     }
923 }
924
925 static int send_full_color_rect(VncState *vs, int x, int y, int w, int h)
926 {
927     int stream = 0;
928     ssize_t bytes;
929
930 #ifdef CONFIG_VNC_PNG
931     if (tight_can_send_png_rect(vs, w, h)) {
932         return send_png_rect(vs, x, y, w, h, NULL);
933     }
934 #endif
935
936     vnc_write_u8(vs, stream << 4); /* no flushing, no filter */
937
938     if (vs->tight.pixel24) {
939         tight_pack24(vs, vs->tight.tight.buffer, w * h, &vs->tight.tight.offset);
940         bytes = 3;
941     } else {
942         bytes = vs->clientds.pf.bytes_per_pixel;
943     }
944
945     bytes = tight_compress_data(vs, stream, w * h * bytes,
946                                 tight_conf[vs->tight.compression].raw_zlib_level,
947                                 Z_DEFAULT_STRATEGY);
948
949     return (bytes >= 0);
950 }
951
952 static int send_solid_rect(VncState *vs)
953 {
954     size_t bytes;
955
956     vnc_write_u8(vs, VNC_TIGHT_FILL << 4); /* no flushing, no filter */
957
958     if (vs->tight.pixel24) {
959         tight_pack24(vs, vs->tight.tight.buffer, 1, &vs->tight.tight.offset);
960         bytes = 3;
961     } else {
962         bytes = vs->clientds.pf.bytes_per_pixel;
963     }
964
965     vnc_write(vs, vs->tight.tight.buffer, bytes);
966     return 1;
967 }
968
969 static int send_mono_rect(VncState *vs, int x, int y,
970                           int w, int h, uint32_t bg, uint32_t fg)
971 {
972     ssize_t bytes;
973     int stream = 1;
974     int level = tight_conf[vs->tight.compression].mono_zlib_level;
975
976 #ifdef CONFIG_VNC_PNG
977     if (tight_can_send_png_rect(vs, w, h)) {
978         int ret;
979         int bpp = vs->clientds.pf.bytes_per_pixel * 8;
980         VncPalette *palette = palette_new(2, bpp);
981
982         palette_put(palette, bg);
983         palette_put(palette, fg);
984         ret = send_png_rect(vs, x, y, w, h, palette);
985         palette_destroy(palette);
986         return ret;
987     }
988 #endif
989
990     bytes = ((w + 7) / 8) * h;
991
992     vnc_write_u8(vs, (stream | VNC_TIGHT_EXPLICIT_FILTER) << 4);
993     vnc_write_u8(vs, VNC_TIGHT_FILTER_PALETTE);
994     vnc_write_u8(vs, 1);
995
996     switch(vs->clientds.pf.bytes_per_pixel) {
997     case 4:
998     {
999         uint32_t buf[2] = {bg, fg};
1000         size_t ret = sizeof (buf);
1001
1002         if (vs->tight.pixel24) {
1003             tight_pack24(vs, (unsigned char*)buf, 2, &ret);
1004         }
1005         vnc_write(vs, buf, ret);
1006
1007         tight_encode_mono_rect32(vs->tight.tight.buffer, w, h, bg, fg);
1008         break;
1009     }
1010     case 2:
1011         vnc_write(vs, &bg, 2);
1012         vnc_write(vs, &fg, 2);
1013         tight_encode_mono_rect16(vs->tight.tight.buffer, w, h, bg, fg);
1014         break;
1015     default:
1016         vnc_write_u8(vs, bg);
1017         vnc_write_u8(vs, fg);
1018         tight_encode_mono_rect8(vs->tight.tight.buffer, w, h, bg, fg);
1019         break;
1020     }
1021     vs->tight.tight.offset = bytes;
1022
1023     bytes = tight_compress_data(vs, stream, bytes, level, Z_DEFAULT_STRATEGY);
1024     return (bytes >= 0);
1025 }
1026
1027 struct palette_cb_priv {
1028     VncState *vs;
1029     uint8_t *header;
1030 #ifdef CONFIG_VNC_PNG
1031     png_colorp png_palette;
1032 #endif
1033 };
1034
1035 static void write_palette(int idx, uint32_t color, void *opaque)
1036 {
1037     struct palette_cb_priv *priv = opaque;
1038     VncState *vs = priv->vs;
1039     uint32_t bytes = vs->clientds.pf.bytes_per_pixel;
1040
1041     if (bytes == 4) {
1042         ((uint32_t*)priv->header)[idx] = color;
1043     } else {
1044         ((uint16_t*)priv->header)[idx] = color;
1045     }
1046 }
1047
1048 static bool send_gradient_rect(VncState *vs, int x, int y, int w, int h)
1049 {
1050     int stream = 3;
1051     int level = tight_conf[vs->tight.compression].gradient_zlib_level;
1052     ssize_t bytes;
1053
1054     if (vs->clientds.pf.bytes_per_pixel == 1)
1055         return send_full_color_rect(vs, x, y, w, h);
1056
1057     vnc_write_u8(vs, (stream | VNC_TIGHT_EXPLICIT_FILTER) << 4);
1058     vnc_write_u8(vs, VNC_TIGHT_FILTER_GRADIENT);
1059
1060     buffer_reserve(&vs->tight.gradient, w * 3 * sizeof (int));
1061
1062     if (vs->tight.pixel24) {
1063         tight_filter_gradient24(vs, vs->tight.tight.buffer, w, h);
1064         bytes = 3;
1065     } else if (vs->clientds.pf.bytes_per_pixel == 4) {
1066         tight_filter_gradient32(vs, (uint32_t *)vs->tight.tight.buffer, w, h);
1067         bytes = 4;
1068     } else {
1069         tight_filter_gradient16(vs, (uint16_t *)vs->tight.tight.buffer, w, h);
1070         bytes = 2;
1071     }
1072
1073     buffer_reset(&vs->tight.gradient);
1074
1075     bytes = w * h * bytes;
1076     vs->tight.tight.offset = bytes;
1077
1078     bytes = tight_compress_data(vs, stream, bytes,
1079                                 level, Z_FILTERED);
1080     return (bytes >= 0);
1081 }
1082
1083 static int send_palette_rect(VncState *vs, int x, int y,
1084                              int w, int h, VncPalette *palette)
1085 {
1086     int stream = 2;
1087     int level = tight_conf[vs->tight.compression].idx_zlib_level;
1088     int colors;
1089     ssize_t bytes;
1090
1091 #ifdef CONFIG_VNC_PNG
1092     if (tight_can_send_png_rect(vs, w, h)) {
1093         return send_png_rect(vs, x, y, w, h, palette);
1094     }
1095 #endif
1096
1097     colors = palette_size(palette);
1098
1099     vnc_write_u8(vs, (stream | VNC_TIGHT_EXPLICIT_FILTER) << 4);
1100     vnc_write_u8(vs, VNC_TIGHT_FILTER_PALETTE);
1101     vnc_write_u8(vs, colors - 1);
1102
1103     switch(vs->clientds.pf.bytes_per_pixel) {
1104     case 4:
1105     {
1106         size_t old_offset, offset;
1107         uint32_t header[palette_size(palette)];
1108         struct palette_cb_priv priv = { vs, (uint8_t *)header };
1109
1110         old_offset = vs->output.offset;
1111         palette_iter(palette, write_palette, &priv);
1112         vnc_write(vs, header, sizeof(header));
1113
1114         if (vs->tight.pixel24) {
1115             tight_pack24(vs, vs->output.buffer + old_offset, colors, &offset);
1116             vs->output.offset = old_offset + offset;
1117         }
1118
1119         tight_encode_indexed_rect32(vs->tight.tight.buffer, w * h, palette);
1120         break;
1121     }
1122     case 2:
1123     {
1124         uint16_t header[palette_size(palette)];
1125         struct palette_cb_priv priv = { vs, (uint8_t *)header };
1126
1127         palette_iter(palette, write_palette, &priv);
1128         vnc_write(vs, header, sizeof(header));
1129         tight_encode_indexed_rect16(vs->tight.tight.buffer, w * h, palette);
1130         break;
1131     }
1132     default:
1133         return -1; /* No palette for 8bits colors */
1134         break;
1135     }
1136     bytes = w * h;
1137     vs->tight.tight.offset = bytes;
1138
1139     bytes = tight_compress_data(vs, stream, bytes,
1140                                 level, Z_DEFAULT_STRATEGY);
1141     return (bytes >= 0);
1142 }
1143
1144 #if defined(CONFIG_VNC_JPEG) || defined(CONFIG_VNC_PNG)
1145 static void rgb_prepare_row24(VncState *vs, uint8_t *dst, int x, int y,
1146                               int count)
1147 {
1148     VncDisplay *vd = vs->vd;
1149     uint32_t *fbptr;
1150     uint32_t pix;
1151
1152     fbptr = (uint32_t *)(vd->server->data + y * ds_get_linesize(vs->ds) +
1153                          x * ds_get_bytes_per_pixel(vs->ds));
1154
1155     while (count--) {
1156         pix = *fbptr++;
1157         *dst++ = (uint8_t)(pix >> vs->ds->surface->pf.rshift);
1158         *dst++ = (uint8_t)(pix >> vs->ds->surface->pf.gshift);
1159         *dst++ = (uint8_t)(pix >> vs->ds->surface->pf.bshift);
1160     }
1161 }
1162
1163 #define DEFINE_RGB_GET_ROW_FUNCTION(bpp)                                \
1164                                                                         \
1165     static void                                                         \
1166     rgb_prepare_row##bpp(VncState *vs, uint8_t *dst,                    \
1167                          int x, int y, int count)                       \
1168     {                                                                   \
1169         VncDisplay *vd = vs->vd;                                        \
1170         uint##bpp##_t *fbptr;                                           \
1171         uint##bpp##_t pix;                                              \
1172         int r, g, b;                                                    \
1173                                                                         \
1174         fbptr = (uint##bpp##_t *)                                       \
1175             (vd->server->data + y * ds_get_linesize(vs->ds) +           \
1176              x * ds_get_bytes_per_pixel(vs->ds));                       \
1177                                                                         \
1178         while (count--) {                                               \
1179             pix = *fbptr++;                                             \
1180                                                                         \
1181             r = (int)((pix >> vs->ds->surface->pf.rshift)               \
1182                       & vs->ds->surface->pf.rmax);                      \
1183             g = (int)((pix >> vs->ds->surface->pf.gshift)               \
1184                       & vs->ds->surface->pf.gmax);                      \
1185             b = (int)((pix >> vs->ds->surface->pf.bshift)               \
1186                       & vs->ds->surface->pf.bmax);                      \
1187                                                                         \
1188             *dst++ = (uint8_t)((r * 255 + vs->ds->surface->pf.rmax / 2) \
1189                                / vs->ds->surface->pf.rmax);             \
1190             *dst++ = (uint8_t)((g * 255 + vs->ds->surface->pf.gmax / 2) \
1191                                / vs->ds->surface->pf.gmax);             \
1192             *dst++ = (uint8_t)((b * 255 + vs->ds->surface->pf.bmax / 2) \
1193                                / vs->ds->surface->pf.bmax);             \
1194         }                                                               \
1195     }
1196
1197 DEFINE_RGB_GET_ROW_FUNCTION(16)
1198 DEFINE_RGB_GET_ROW_FUNCTION(32)
1199
1200 static void rgb_prepare_row(VncState *vs, uint8_t *dst, int x, int y,
1201                             int count)
1202 {
1203     if (ds_get_bytes_per_pixel(vs->ds) == 4) {
1204         if (vs->ds->surface->pf.rmax == 0xFF &&
1205             vs->ds->surface->pf.gmax == 0xFF &&
1206             vs->ds->surface->pf.bmax == 0xFF) {
1207             rgb_prepare_row24(vs, dst, x, y, count);
1208         } else {
1209             rgb_prepare_row32(vs, dst, x, y, count);
1210         }
1211     } else {
1212         rgb_prepare_row16(vs, dst, x, y, count);
1213     }
1214 }
1215 #endif /* CONFIG_VNC_JPEG or CONFIG_VNC_PNG */
1216
1217 /*
1218  * JPEG compression stuff.
1219  */
1220 #ifdef CONFIG_VNC_JPEG
1221 /*
1222  * Destination manager implementation for JPEG library.
1223  */
1224
1225 /* This is called once per encoding */
1226 static void jpeg_init_destination(j_compress_ptr cinfo)
1227 {
1228     VncState *vs = cinfo->client_data;
1229     Buffer *buffer = &vs->tight.jpeg;
1230
1231     cinfo->dest->next_output_byte = (JOCTET *)buffer->buffer + buffer->offset;
1232     cinfo->dest->free_in_buffer = (size_t)(buffer->capacity - buffer->offset);
1233 }
1234
1235 /* This is called when we ran out of buffer (shouldn't happen!) */
1236 static boolean jpeg_empty_output_buffer(j_compress_ptr cinfo)
1237 {
1238     VncState *vs = cinfo->client_data;
1239     Buffer *buffer = &vs->tight.jpeg;
1240
1241     buffer->offset = buffer->capacity;
1242     buffer_reserve(buffer, 2048);
1243     jpeg_init_destination(cinfo);
1244     return TRUE;
1245 }
1246
1247 /* This is called when we are done processing data */
1248 static void jpeg_term_destination(j_compress_ptr cinfo)
1249 {
1250     VncState *vs = cinfo->client_data;
1251     Buffer *buffer = &vs->tight.jpeg;
1252
1253     buffer->offset = buffer->capacity - cinfo->dest->free_in_buffer;
1254 }
1255
1256 static int send_jpeg_rect(VncState *vs, int x, int y, int w, int h, int quality)
1257 {
1258     struct jpeg_compress_struct cinfo;
1259     struct jpeg_error_mgr jerr;
1260     struct jpeg_destination_mgr manager;
1261     JSAMPROW row[1];
1262     uint8_t *buf;
1263     int dy;
1264
1265     if (ds_get_bytes_per_pixel(vs->ds) == 1)
1266         return send_full_color_rect(vs, x, y, w, h);
1267
1268     buffer_reserve(&vs->tight.jpeg, 2048);
1269
1270     cinfo.err = jpeg_std_error(&jerr);
1271     jpeg_create_compress(&cinfo);
1272
1273     cinfo.client_data = vs;
1274     cinfo.image_width = w;
1275     cinfo.image_height = h;
1276     cinfo.input_components = 3;
1277     cinfo.in_color_space = JCS_RGB;
1278
1279     jpeg_set_defaults(&cinfo);
1280     jpeg_set_quality(&cinfo, quality, true);
1281
1282     manager.init_destination = jpeg_init_destination;
1283     manager.empty_output_buffer = jpeg_empty_output_buffer;
1284     manager.term_destination = jpeg_term_destination;
1285     cinfo.dest = &manager;
1286
1287     jpeg_start_compress(&cinfo, true);
1288
1289     buf = qemu_malloc(w * 3);
1290     row[0] = buf;
1291     for (dy = 0; dy < h; dy++) {
1292         rgb_prepare_row(vs, buf, x, y + dy, w);
1293         jpeg_write_scanlines(&cinfo, row, 1);
1294     }
1295     qemu_free(buf);
1296
1297     jpeg_finish_compress(&cinfo);
1298     jpeg_destroy_compress(&cinfo);
1299
1300     vnc_write_u8(vs, VNC_TIGHT_JPEG << 4);
1301
1302     tight_send_compact_size(vs, vs->tight.jpeg.offset);
1303     vnc_write(vs, vs->tight.jpeg.buffer, vs->tight.jpeg.offset);
1304     buffer_reset(&vs->tight.jpeg);
1305
1306     return 1;
1307 }
1308 #endif /* CONFIG_VNC_JPEG */
1309
1310 /*
1311  * PNG compression stuff.
1312  */
1313 #ifdef CONFIG_VNC_PNG
1314 static void write_png_palette(int idx, uint32_t pix, void *opaque)
1315 {
1316     struct palette_cb_priv *priv = opaque;
1317     VncState *vs = priv->vs;
1318     png_colorp color = &priv->png_palette[idx];
1319
1320     if (vs->tight.pixel24)
1321     {
1322         color->red = (pix >> vs->clientds.pf.rshift) & vs->clientds.pf.rmax;
1323         color->green = (pix >> vs->clientds.pf.gshift) & vs->clientds.pf.gmax;
1324         color->blue = (pix >> vs->clientds.pf.bshift) & vs->clientds.pf.bmax;
1325     }
1326     else
1327     {
1328         int red, green, blue;
1329
1330         red = (pix >> vs->clientds.pf.rshift) & vs->clientds.pf.rmax;
1331         green = (pix >> vs->clientds.pf.gshift) & vs->clientds.pf.gmax;
1332         blue = (pix >> vs->clientds.pf.bshift) & vs->clientds.pf.bmax;
1333         color->red = ((red * 255 + vs->clientds.pf.rmax / 2) /
1334                       vs->clientds.pf.rmax);
1335         color->green = ((green * 255 + vs->clientds.pf.gmax / 2) /
1336                         vs->clientds.pf.gmax);
1337         color->blue = ((blue * 255 + vs->clientds.pf.bmax / 2) /
1338                        vs->clientds.pf.bmax);
1339     }
1340 }
1341
1342 static void png_write_data(png_structp png_ptr, png_bytep data,
1343                            png_size_t length)
1344 {
1345     VncState *vs = png_get_io_ptr(png_ptr);
1346
1347     buffer_reserve(&vs->tight.png, vs->tight.png.offset + length);
1348     memcpy(vs->tight.png.buffer + vs->tight.png.offset, data, length);
1349
1350     vs->tight.png.offset += length;
1351 }
1352
1353 static void png_flush_data(png_structp png_ptr)
1354 {
1355 }
1356
1357 static void *vnc_png_malloc(png_structp png_ptr, png_size_t size)
1358 {
1359     return qemu_malloc(size);
1360 }
1361
1362 static void vnc_png_free(png_structp png_ptr, png_voidp ptr)
1363 {
1364     qemu_free(ptr);
1365 }
1366
1367 static int send_png_rect(VncState *vs, int x, int y, int w, int h,
1368                          VncPalette *palette)
1369 {
1370     png_byte color_type;
1371     png_structp png_ptr;
1372     png_infop info_ptr;
1373     png_colorp png_palette = NULL;
1374     int level = tight_png_conf[vs->tight.compression].png_zlib_level;
1375     int filters = tight_png_conf[vs->tight.compression].png_filters;
1376     uint8_t *buf;
1377     int dy;
1378
1379     png_ptr = png_create_write_struct_2(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL,
1380                                         NULL, vnc_png_malloc, vnc_png_free);
1381
1382     if (png_ptr == NULL)
1383         return -1;
1384
1385     info_ptr = png_create_info_struct(png_ptr);
1386
1387     if (info_ptr == NULL) {
1388         png_destroy_write_struct(&png_ptr, NULL);
1389         return -1;
1390     }
1391
1392     png_set_write_fn(png_ptr, (void *) vs, png_write_data, png_flush_data);
1393     png_set_compression_level(png_ptr, level);
1394     png_set_filter(png_ptr, PNG_FILTER_TYPE_DEFAULT, filters);
1395
1396     if (palette) {
1397         color_type = PNG_COLOR_TYPE_PALETTE;
1398     } else {
1399         color_type = PNG_COLOR_TYPE_RGB;
1400     }
1401
1402     png_set_IHDR(png_ptr, info_ptr, w, h,
1403                  8, color_type, PNG_INTERLACE_NONE,
1404                  PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT);
1405
1406     if (color_type == PNG_COLOR_TYPE_PALETTE) {
1407         struct palette_cb_priv priv;
1408
1409         png_palette = png_malloc(png_ptr, sizeof(*png_palette) *
1410                                  palette_size(palette));
1411
1412         priv.vs = vs;
1413         priv.png_palette = png_palette;
1414         palette_iter(palette, write_png_palette, &priv);
1415
1416         png_set_PLTE(png_ptr, info_ptr, png_palette, palette_size(palette));
1417
1418         if (vs->clientds.pf.bytes_per_pixel == 4) {
1419             tight_encode_indexed_rect32(vs->tight.tight.buffer, w * h, palette);
1420         } else {
1421             tight_encode_indexed_rect16(vs->tight.tight.buffer, w * h, palette);
1422         }
1423     }
1424
1425     png_write_info(png_ptr, info_ptr);
1426
1427     buffer_reserve(&vs->tight.png, 2048);
1428     buf = qemu_malloc(w * 3);
1429     for (dy = 0; dy < h; dy++)
1430     {
1431         if (color_type == PNG_COLOR_TYPE_PALETTE) {
1432             memcpy(buf, vs->tight.tight.buffer + (dy * w), w);
1433         } else {
1434             rgb_prepare_row(vs, buf, x, y + dy, w);
1435         }
1436         png_write_row(png_ptr, buf);
1437     }
1438     qemu_free(buf);
1439
1440     png_write_end(png_ptr, NULL);
1441
1442     if (color_type == PNG_COLOR_TYPE_PALETTE) {
1443         png_free(png_ptr, png_palette);
1444     }
1445
1446     png_destroy_write_struct(&png_ptr, &info_ptr);
1447
1448     vnc_write_u8(vs, VNC_TIGHT_PNG << 4);
1449
1450     tight_send_compact_size(vs, vs->tight.png.offset);
1451     vnc_write(vs, vs->tight.png.buffer, vs->tight.png.offset);
1452     buffer_reset(&vs->tight.png);
1453     return 1;
1454 }
1455 #endif /* CONFIG_VNC_PNG */
1456
1457 static void vnc_tight_start(VncState *vs)
1458 {
1459     buffer_reset(&vs->tight.tight);
1460
1461     // make the output buffer be the zlib buffer, so we can compress it later
1462     vs->tight.tmp = vs->output;
1463     vs->output = vs->tight.tight;
1464 }
1465
1466 static void vnc_tight_stop(VncState *vs)
1467 {
1468     // switch back to normal output/zlib buffers
1469     vs->tight.tight = vs->output;
1470     vs->output = vs->tight.tmp;
1471 }
1472
1473 static int send_sub_rect_nojpeg(VncState *vs, int x, int y, int w, int h,
1474                                 int bg, int fg, int colors, VncPalette *palette)
1475 {
1476     int ret;
1477
1478     if (colors == 0) {
1479         if (tight_detect_smooth_image(vs, w, h)) {
1480             ret = send_gradient_rect(vs, x, y, w, h);
1481         } else {
1482             ret = send_full_color_rect(vs, x, y, w, h);
1483         }
1484     } else if (colors == 1) {
1485         ret = send_solid_rect(vs);
1486     } else if (colors == 2) {
1487         ret = send_mono_rect(vs, x, y, w, h, bg, fg);
1488     } else if (colors <= 256) {
1489         ret = send_palette_rect(vs, x, y, w, h, palette);
1490     } else {
1491         ret = 0;
1492     }
1493     return ret;
1494 }
1495
1496 #ifdef CONFIG_VNC_JPEG
1497 static int send_sub_rect_jpeg(VncState *vs, int x, int y, int w, int h,
1498                               int bg, int fg, int colors,
1499                               VncPalette *palette, bool force)
1500 {
1501     int ret;
1502
1503     if (colors == 0) {
1504         if (force || (tight_jpeg_conf[vs->tight.quality].jpeg_full &&
1505                       tight_detect_smooth_image(vs, w, h))) {
1506             int quality = tight_conf[vs->tight.quality].jpeg_quality;
1507
1508             ret = send_jpeg_rect(vs, x, y, w, h, quality);
1509         } else {
1510             ret = send_full_color_rect(vs, x, y, w, h);
1511         }
1512     } else if (colors == 1) {
1513         ret = send_solid_rect(vs);
1514     } else if (colors == 2) {
1515         ret = send_mono_rect(vs, x, y, w, h, bg, fg);
1516     } else if (colors <= 256) {
1517         if (force || (colors > 96 &&
1518                       tight_jpeg_conf[vs->tight.quality].jpeg_idx &&
1519                       tight_detect_smooth_image(vs, w, h))) {
1520             int quality = tight_conf[vs->tight.quality].jpeg_quality;
1521
1522             ret = send_jpeg_rect(vs, x, y, w, h, quality);
1523         } else {
1524             ret = send_palette_rect(vs, x, y, w, h, palette);
1525         }
1526     } else {
1527         ret = 0;
1528     }
1529     return ret;
1530 }
1531 #endif
1532
1533 static int send_sub_rect(VncState *vs, int x, int y, int w, int h)
1534 {
1535     VncPalette *palette = NULL;
1536     uint32_t bg = 0, fg = 0;
1537     int colors;
1538     int ret = 0;
1539     bool force_jpeg = false;
1540     bool allow_jpeg = true;
1541
1542     vnc_framebuffer_update(vs, x, y, w, h, vs->tight.type);
1543
1544     vnc_tight_start(vs);
1545     vnc_raw_send_framebuffer_update(vs, x, y, w, h);
1546     vnc_tight_stop(vs);
1547
1548 #ifdef CONFIG_VNC_JPEG
1549     if (!vs->vd->non_adaptive && vs->tight.quality != (uint8_t)-1) {
1550         double freq = vnc_update_freq(vs, x, y, w, h);
1551
1552         if (freq < tight_jpeg_conf[vs->tight.quality].jpeg_freq_min) {
1553             allow_jpeg = false;
1554         }
1555         if (freq >= tight_jpeg_conf[vs->tight.quality].jpeg_freq_threshold) {
1556             force_jpeg = true;
1557             vnc_sent_lossy_rect(vs, x, y, w, h);
1558         }
1559     }
1560 #endif
1561
1562     colors = tight_fill_palette(vs, x, y, w * h, &fg, &bg, &palette);
1563
1564 #ifdef CONFIG_VNC_JPEG
1565     if (allow_jpeg && vs->tight.quality != (uint8_t)-1) {
1566         ret = send_sub_rect_jpeg(vs, x, y, w, h, bg, fg, colors, palette,
1567                                  force_jpeg);
1568     } else {
1569         ret = send_sub_rect_nojpeg(vs, x, y, w, h, bg, fg, colors, palette);
1570     }
1571 #else
1572     ret = send_sub_rect_nojpeg(vs, x, y, w, h, bg, fg, colors, palette);
1573 #endif
1574
1575     palette_destroy(palette);
1576     return ret;
1577 }
1578
1579 static int send_sub_rect_solid(VncState *vs, int x, int y, int w, int h)
1580 {
1581     vnc_framebuffer_update(vs, x, y, w, h, vs->tight.type);
1582
1583     vnc_tight_start(vs);
1584     vnc_raw_send_framebuffer_update(vs, x, y, w, h);
1585     vnc_tight_stop(vs);
1586
1587     return send_solid_rect(vs);
1588 }
1589
1590 static int send_rect_simple(VncState *vs, int x, int y, int w, int h,
1591                             bool split)
1592 {
1593     int max_size, max_width;
1594     int max_sub_width, max_sub_height;
1595     int dx, dy;
1596     int rw, rh;
1597     int n = 0;
1598
1599     max_size = tight_conf[vs->tight.compression].max_rect_size;
1600     max_width = tight_conf[vs->tight.compression].max_rect_width;
1601
1602     if (split && (w > max_width || w * h > max_size)) {
1603         max_sub_width = (w > max_width) ? max_width : w;
1604         max_sub_height = max_size / max_sub_width;
1605
1606         for (dy = 0; dy < h; dy += max_sub_height) {
1607             for (dx = 0; dx < w; dx += max_width) {
1608                 rw = MIN(max_sub_width, w - dx);
1609                 rh = MIN(max_sub_height, h - dy);
1610                 n += send_sub_rect(vs, x+dx, y+dy, rw, rh);
1611             }
1612         }
1613     } else {
1614         n += send_sub_rect(vs, x, y, w, h);
1615     }
1616
1617     return n;
1618 }
1619
1620 static int find_large_solid_color_rect(VncState *vs, int x, int y,
1621                                        int w, int h, int max_rows)
1622 {
1623     int dx, dy, dw, dh;
1624     int n = 0;
1625
1626     /* Try to find large solid-color areas and send them separately. */
1627
1628     for (dy = y; dy < y + h; dy += VNC_TIGHT_MAX_SPLIT_TILE_SIZE) {
1629
1630         /* If a rectangle becomes too large, send its upper part now. */
1631
1632         if (dy - y >= max_rows) {
1633             n += send_rect_simple(vs, x, y, w, max_rows, true);
1634             y += max_rows;
1635             h -= max_rows;
1636         }
1637
1638         dh = MIN(VNC_TIGHT_MAX_SPLIT_TILE_SIZE, (y + h - dy));
1639
1640         for (dx = x; dx < x + w; dx += VNC_TIGHT_MAX_SPLIT_TILE_SIZE) {
1641             uint32_t color_value;
1642             int x_best, y_best, w_best, h_best;
1643
1644             dw = MIN(VNC_TIGHT_MAX_SPLIT_TILE_SIZE, (x + w - dx));
1645
1646             if (!check_solid_tile(vs, dx, dy, dw, dh, &color_value, false)) {
1647                 continue ;
1648             }
1649
1650             /* Get dimensions of solid-color area. */
1651
1652             find_best_solid_area(vs, dx, dy, w - (dx - x), h - (dy - y),
1653                                  color_value, &w_best, &h_best);
1654
1655             /* Make sure a solid rectangle is large enough
1656                (or the whole rectangle is of the same color). */
1657
1658             if (w_best * h_best != w * h &&
1659                 w_best * h_best < VNC_TIGHT_MIN_SOLID_SUBRECT_SIZE) {
1660                 continue;
1661             }
1662
1663             /* Try to extend solid rectangle to maximum size. */
1664
1665             x_best = dx; y_best = dy;
1666             extend_solid_area(vs, x, y, w, h, color_value,
1667                               &x_best, &y_best, &w_best, &h_best);
1668
1669             /* Send rectangles at top and left to solid-color area. */
1670
1671             if (y_best != y) {
1672                 n += send_rect_simple(vs, x, y, w, y_best-y, true);
1673             }
1674             if (x_best != x) {
1675                 n += tight_send_framebuffer_update(vs, x, y_best,
1676                                                    x_best-x, h_best);
1677             }
1678
1679             /* Send solid-color rectangle. */
1680             n += send_sub_rect_solid(vs, x_best, y_best, w_best, h_best);
1681
1682             /* Send remaining rectangles (at right and bottom). */
1683
1684             if (x_best + w_best != x + w) {
1685                 n += tight_send_framebuffer_update(vs, x_best+w_best,
1686                                                    y_best,
1687                                                    w-(x_best-x)-w_best,
1688                                                    h_best);
1689             }
1690             if (y_best + h_best != y + h) {
1691                 n += tight_send_framebuffer_update(vs, x, y_best+h_best,
1692                                                    w, h-(y_best-y)-h_best);
1693             }
1694
1695             /* Return after all recursive calls are done. */
1696             return n;
1697         }
1698     }
1699     return n + send_rect_simple(vs, x, y, w, h, true);
1700 }
1701
1702 static int tight_send_framebuffer_update(VncState *vs, int x, int y,
1703                                          int w, int h)
1704 {
1705     int max_rows;
1706
1707     if (vs->clientds.pf.bytes_per_pixel == 4 && vs->clientds.pf.rmax == 0xFF &&
1708         vs->clientds.pf.bmax == 0xFF && vs->clientds.pf.gmax == 0xFF) {
1709         vs->tight.pixel24 = true;
1710     } else {
1711         vs->tight.pixel24 = false;
1712     }
1713
1714     if (vs->tight.quality != (uint8_t)-1) {
1715         double freq = vnc_update_freq(vs, x, y, w, h);
1716
1717         if (freq > tight_jpeg_conf[vs->tight.quality].jpeg_freq_threshold) {
1718             return send_rect_simple(vs, x, y, w, h, false);
1719         }
1720     }
1721
1722     if (w * h < VNC_TIGHT_MIN_SPLIT_RECT_SIZE) {
1723         return send_rect_simple(vs, x, y, w, h, true);
1724     }
1725
1726     /* Calculate maximum number of rows in one non-solid rectangle. */
1727
1728     max_rows = tight_conf[vs->tight.compression].max_rect_size;
1729     max_rows /= MIN(tight_conf[vs->tight.compression].max_rect_width, w);
1730
1731     return find_large_solid_color_rect(vs, x, y, w, h, max_rows);
1732 }
1733
1734 int vnc_tight_send_framebuffer_update(VncState *vs, int x, int y,
1735                                       int w, int h)
1736 {
1737     vs->tight.type = VNC_ENCODING_TIGHT;
1738     return tight_send_framebuffer_update(vs, x, y, w, h);
1739 }
1740
1741 int vnc_tight_png_send_framebuffer_update(VncState *vs, int x, int y,
1742                                           int w, int h)
1743 {
1744     vs->tight.type = VNC_ENCODING_TIGHT_PNG;
1745     return tight_send_framebuffer_update(vs, x, y, w, h);
1746 }
1747
1748 void vnc_tight_clear(VncState *vs)
1749 {
1750     int i;
1751     for (i=0; i<ARRAY_SIZE(vs->tight.stream); i++) {
1752         if (vs->tight.stream[i].opaque) {
1753             deflateEnd(&vs->tight.stream[i]);
1754         }
1755     }
1756
1757     buffer_free(&vs->tight.tight);
1758     buffer_free(&vs->tight.zlib);
1759     buffer_free(&vs->tight.gradient);
1760 #ifdef CONFIG_VNC_JPEG
1761     buffer_free(&vs->tight.jpeg);
1762 #endif
1763 #ifdef CONFIG_VNC_PNG
1764     buffer_free(&vs->tight.png);
1765 #endif
1766 }
This page took 0.125328 seconds and 4 git commands to generate.