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