FreeRDP
Loading...
Searching...
No Matches
clear.c
1
22
23#include <freerdp/config.h>
24
25#include <winpr/crt.h>
26#include <winpr/print.h>
27#include <winpr/bitstream.h>
28
29#include <freerdp/codec/color.h>
30#include <freerdp/codec/clear.h>
31#include <freerdp/log.h>
32
33#define TAG FREERDP_TAG("codec.clear")
34
35#define CLEARCODEC_FLAG_GLYPH_INDEX 0x01
36#define CLEARCODEC_FLAG_GLYPH_HIT 0x02
37#define CLEARCODEC_FLAG_CACHE_RESET 0x04
38
39#define CLEARCODEC_VBAR_SIZE 32768
40#define CLEARCODEC_VBAR_SHORT_SIZE 16384
41
42/* Encoder-only: open-addressed hash index mapping V-Bar column content to its slot in
43 * clear->VBarStorage, so clear_compress_bands_data() can find VBAR_CACHE_HIT candidates in
44 * O(1) instead of scanning the whole cache. Must be a power of two, comfortably larger than
45 * CLEARCODEC_VBAR_SIZE so insert() always finds a free/tombstoned slot. */
46#define CLEAR_VBAR_HASH_SIZE 65536u
47#define CLEAR_VBAR_HASH_EMPTY 0u
48#define CLEAR_VBAR_HASH_DELETED 0xFFFFFFFFu
49#define CLEAR_BAND_MAX_HEIGHT 52u
50
51typedef struct
52{
53 UINT32 size;
54 UINT32 count;
55 UINT32* pixels;
56} CLEAR_GLYPH_ENTRY;
57
58typedef struct
59{
60 UINT32 size;
61 UINT32 count;
62 BYTE* pixels;
63} CLEAR_VBAR_ENTRY;
64
65struct S_CLEAR_CONTEXT
66{
67 BOOL Compressor;
68 NSC_CONTEXT* nsc;
69 UINT32 seqNumber;
70 BYTE* TempBuffer;
71 size_t TempSize;
72 UINT32 format;
73 BOOL formatSet;
74 CLEAR_GLYPH_ENTRY GlyphCache[4000];
75 UINT32 VBarStorageCursor;
76 CLEAR_VBAR_ENTRY VBarStorage[CLEARCODEC_VBAR_SIZE];
77 UINT32 ShortVBarStorageCursor;
78 CLEAR_VBAR_ENTRY ShortVBarStorage[CLEARCODEC_VBAR_SHORT_SIZE];
79 wLog* log;
80 wStream* bs; /* clear_compress() output, owned by this context, Compressor only */
81 UINT32* VBarHashSlots; /* clear_compress() V-Bar lookup index, Compressor only, see above */
82
83 /* Compressor only: NSCodec subcodec input (BGRX32, bottom-up, padded) and output */
84 BYTE* NscBuffer;
85 size_t NscBufferSize;
86 wStream* nscStream;
87
88 /* Compressor only: open-addressed set of the colors seen by clear_count_colors() */
89 UINT32* ColorSet;
90 size_t ColorSetSize;
91};
92
93static const UINT32 CLEAR_LOG2_FLOOR[256] = {
94 0, 0, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
95 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
96 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
97 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
98 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
99 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
100 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
101 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7
102};
103
104static const BYTE CLEAR_8BIT_MASKS[9] = { 0x00, 0x01, 0x03, 0x07, 0x0F, 0x1F, 0x3F, 0x7F, 0xFF };
105
106static void clear_reset_vbar_storage(CLEAR_CONTEXT* WINPR_RESTRICT clear, BOOL zero)
107{
108 if (zero)
109 {
110 for (size_t i = 0; i < ARRAYSIZE(clear->VBarStorage); i++)
111 winpr_aligned_free(clear->VBarStorage[i].pixels);
112
113 ZeroMemory(clear->VBarStorage, sizeof(clear->VBarStorage));
114
115 if (clear->VBarHashSlots)
116 ZeroMemory(clear->VBarHashSlots, CLEAR_VBAR_HASH_SIZE * sizeof(UINT32));
117 }
118
119 clear->VBarStorageCursor = 0;
120
121 if (zero)
122 {
123 for (size_t i = 0; i < ARRAYSIZE(clear->ShortVBarStorage); i++)
124 winpr_aligned_free(clear->ShortVBarStorage[i].pixels);
125
126 ZeroMemory(clear->ShortVBarStorage, sizeof(clear->ShortVBarStorage));
127 }
128
129 clear->ShortVBarStorageCursor = 0;
130}
131
132static void clear_reset_glyph_cache(CLEAR_CONTEXT* WINPR_RESTRICT clear)
133{
134 for (size_t i = 0; i < ARRAYSIZE(clear->GlyphCache); i++)
135 winpr_aligned_free(clear->GlyphCache[i].pixels);
136
137 ZeroMemory(clear->GlyphCache, sizeof(clear->GlyphCache));
138}
139
140static BOOL convert_color(BYTE* WINPR_RESTRICT dst, UINT32 nDstStep, UINT32 DstFormat, UINT32 nXDst,
141 UINT32 nYDst, UINT32 nWidth, UINT32 nHeight,
142 const BYTE* WINPR_RESTRICT src, UINT32 nSrcStep, UINT32 SrcFormat,
143 UINT32 nDstWidth, UINT32 nDstHeight,
144 const gdiPalette* WINPR_RESTRICT palette)
145{
146 if (nWidth + nXDst > nDstWidth)
147 nWidth = nDstWidth - nXDst;
148
149 if (nHeight + nYDst > nDstHeight)
150 nHeight = nDstHeight - nYDst;
151
152 return freerdp_image_copy_no_overlap(dst, DstFormat, nDstStep, nXDst, nYDst, nWidth, nHeight,
153 src, SrcFormat, nSrcStep, 0, 0, palette,
154 FREERDP_KEEP_DST_ALPHA);
155}
156
157static BOOL clear_decompress_nscodec(wLog* log, NSC_CONTEXT* WINPR_RESTRICT nsc, UINT32 width,
158 UINT32 height, wStream* WINPR_RESTRICT s,
159 UINT32 bitmapDataByteCount, BYTE* WINPR_RESTRICT pDstData,
160 UINT32 DstFormat, UINT32 nDstStep, UINT32 nXDstRel,
161 UINT32 nYDstRel, UINT32 nDstWidth, UINT32 nDstHeight)
162{
163 BOOL rc = 0;
164
165 if (!Stream_CheckAndLogRequiredLengthWLog(log, s, bitmapDataByteCount))
166 return FALSE;
167
168 rc = nsc_process_message(nsc, 32, width, height, Stream_Pointer(s), bitmapDataByteCount,
169 pDstData, DstFormat, nDstStep, nXDstRel, nYDstRel, nDstWidth,
170 nDstHeight, FREERDP_FLIP_NONE);
171 Stream_Seek(s, bitmapDataByteCount);
172 return rc;
173}
174
175static BOOL clear_decompress_subcode_rlex(wLog* log, wStream* WINPR_RESTRICT s,
176 UINT32 bitmapDataByteCount, UINT32 width, UINT32 height,
177 BYTE* WINPR_RESTRICT pDstData, UINT32 DstFormat,
178 UINT32 nDstStep, UINT32 nXDstRel, UINT32 nYDstRel,
179 UINT32 nDstWidth, UINT32 nDstHeight)
180{
181 UINT32 x = 0;
182 UINT32 y = 0;
183 UINT32 bitmapDataOffset = 0;
184 BYTE paletteCount = 0;
185 UINT32 palette[128] = WINPR_C_ARRAY_INIT;
186
187 if (!Stream_CheckAndLogRequiredLengthWLog(log, s, bitmapDataByteCount))
188 return FALSE;
189
190 if (!Stream_CheckAndLogRequiredLengthWLog(log, s, 1))
191 return FALSE;
192 Stream_Read_UINT8(s, paletteCount);
193 bitmapDataOffset = 1 + (paletteCount * 3);
194
195 if ((paletteCount > 127) || (paletteCount < 1))
196 {
197 WLog_Print(log, WLOG_ERROR, "paletteCount %" PRIu8 "", paletteCount);
198 return FALSE;
199 }
200
201 if (!Stream_CheckAndLogRequiredLengthOfSizeWLog(log, s, paletteCount, 3ull))
202 return FALSE;
203
204 for (UINT32 i = 0; i < paletteCount; i++)
205 {
206 const BYTE b = Stream_Get_UINT8(s);
207 const BYTE g = Stream_Get_UINT8(s);
208 const BYTE r = Stream_Get_UINT8(s);
209 palette[i] = FreeRDPGetColor(DstFormat, r, g, b, 0xFF);
210 }
211
212 UINT32 pixelIndex = 0;
213 if ((height == 0) || (width == 0) || (width > UINT32_MAX / height))
214 return FALSE;
215
216 const UINT32 pixelCount = width * height;
217 const UINT32 numBits = CLEAR_LOG2_FLOOR[paletteCount - 1] + 1;
218
219 while (bitmapDataOffset < bitmapDataByteCount)
220 {
221 if (!Stream_CheckAndLogRequiredLengthWLog(log, s, 2))
222 return FALSE;
223
224 const UINT32 tmp = Stream_Get_UINT8(s);
225 UINT32 runLengthFactor = Stream_Get_UINT8(s);
226
227 bitmapDataOffset += 2;
228 const BYTE suiteDepth = (tmp >> numBits) & CLEAR_8BIT_MASKS[(8 - numBits)];
229 const BYTE stopIndex = tmp & CLEAR_8BIT_MASKS[numBits];
230 const BYTE startIndex = stopIndex - suiteDepth;
231
232 if (runLengthFactor >= 0xFF)
233 {
234 if (!Stream_CheckAndLogRequiredLengthWLog(log, s, 2))
235 return FALSE;
236
237 Stream_Read_UINT16(s, runLengthFactor);
238 bitmapDataOffset += 2;
239
240 if (runLengthFactor >= 0xFFFF)
241 {
242 if (!Stream_CheckAndLogRequiredLengthWLog(log, s, 4))
243 return FALSE;
244
245 Stream_Read_UINT32(s, runLengthFactor);
246 bitmapDataOffset += 4;
247 }
248 }
249
250 if (startIndex >= paletteCount)
251 {
252 WLog_Print(log, WLOG_ERROR, "startIndex %" PRIu8 " > paletteCount %" PRIu8 "]",
253 startIndex, paletteCount);
254 return FALSE;
255 }
256
257 if (stopIndex >= paletteCount)
258 {
259 WLog_Print(log, WLOG_ERROR, "stopIndex %" PRIu8 " > paletteCount %" PRIu8 "]",
260 stopIndex, paletteCount);
261 return FALSE;
262 }
263
264 BYTE suiteIndex = startIndex;
265
266 if (suiteIndex > 127)
267 {
268 WLog_Print(log, WLOG_ERROR, "suiteIndex %" PRIu8 " > 127]", suiteIndex);
269 return FALSE;
270 }
271
272 const UINT32 color = palette[suiteIndex];
273 if ((pixelIndex > UINT32_MAX - runLengthFactor) ||
274 ((pixelIndex + runLengthFactor) > pixelCount))
275 {
276 WLog_Print(log, WLOG_ERROR,
277 "pixelIndex %" PRIu32 " + runLengthFactor %" PRIu32 " > pixelCount %" PRIu32
278 "",
279 pixelIndex, runLengthFactor, pixelCount);
280 return FALSE;
281 }
282
283 for (UINT32 i = 0; i < runLengthFactor; i++)
284 {
285 BYTE* pTmpData = &pDstData[(nXDstRel + x) * FreeRDPGetBytesPerPixel(DstFormat) +
286 (nYDstRel + y) * nDstStep];
287
288 if ((nXDstRel + x < nDstWidth) && (nYDstRel + y < nDstHeight))
289 FreeRDPWriteColor(pTmpData, DstFormat, color);
290
291 if (++x >= width)
292 {
293 y++;
294 x = 0;
295 }
296 }
297
298 pixelIndex += runLengthFactor;
299
300 if ((pixelIndex > UINT32_MAX - 1 - suiteDepth) ||
301 ((pixelIndex + (suiteDepth + 1)) > pixelCount))
302 {
303 WLog_Print(log, WLOG_ERROR,
304 "pixelIndex %" PRIu32 " + suiteDepth %" PRIu8 " + 1 > pixelCount %" PRIu32
305 "",
306 pixelIndex, suiteDepth, pixelCount);
307 return FALSE;
308 }
309
310 for (UINT32 i = 0; i <= suiteDepth; i++)
311 {
312 BYTE* pTmpData = &pDstData[(nXDstRel + x) * FreeRDPGetBytesPerPixel(DstFormat) +
313 (nYDstRel + y) * nDstStep];
314 UINT32 ccolor = palette[suiteIndex];
315
316 if (suiteIndex > 127)
317 {
318 WLog_Print(log, WLOG_ERROR, "suiteIndex %" PRIu8 " > 127", suiteIndex);
319 return FALSE;
320 }
321
322 suiteIndex++;
323
324 if ((nXDstRel + x < nDstWidth) && (nYDstRel + y < nDstHeight))
325 FreeRDPWriteColor(pTmpData, DstFormat, ccolor);
326
327 if (++x >= width)
328 {
329 y++;
330 x = 0;
331 }
332 }
333
334 pixelIndex += (suiteDepth + 1);
335 }
336
337 if (pixelIndex != pixelCount)
338 {
339 WLog_Print(log, WLOG_ERROR, "pixelIndex %" PRIu32 " != pixelCount %" PRIu32 "", pixelIndex,
340 pixelCount);
341 return FALSE;
342 }
343
344 return TRUE;
345}
346
347static BOOL clear_resize_buffer(CLEAR_CONTEXT* WINPR_RESTRICT clear, UINT32 width, UINT32 height)
348{
349 if (!clear)
350 return FALSE;
351
352 const UINT64 size = 1ull * (width + 16ull) * (height + 16ull);
353 const size_t bpp = FreeRDPGetBytesPerPixel(clear->format);
354 if (size > UINT32_MAX / bpp)
355 return FALSE;
356
357 if (size > clear->TempSize / bpp)
358 {
359 BYTE* tmp = (BYTE*)winpr_aligned_recalloc(clear->TempBuffer,
360 WINPR_ASSERTING_INT_CAST(size_t, size), bpp, 32);
361
362 if (!tmp)
363 {
364 WLog_Print(clear->log, WLOG_ERROR,
365 "clear->TempBuffer winpr_aligned_recalloc failed for %" PRIu64 " bytes",
366 size);
367 return FALSE;
368 }
369
370 clear->TempSize = WINPR_ASSERTING_INT_CAST(size_t, size* bpp);
371 clear->TempBuffer = tmp;
372 }
373
374 return TRUE;
375}
376
377static BOOL clear_decompress_residual_data(CLEAR_CONTEXT* WINPR_RESTRICT clear,
378 wStream* WINPR_RESTRICT s, UINT32 residualByteCount,
379 UINT32 nWidth, UINT32 nHeight,
380 BYTE* WINPR_RESTRICT pDstData, UINT32 DstFormat,
381 UINT32 nDstStep, UINT32 nXDst, UINT32 nYDst,
382 UINT32 nDstWidth, UINT32 nDstHeight,
383 const gdiPalette* WINPR_RESTRICT palette)
384{
385 UINT32 nSrcStep = 0;
386 UINT32 suboffset = 0;
387 BYTE* dstBuffer = nullptr;
388 UINT32 pixelIndex = 0;
389 UINT32 pixelCount = 0;
390
391 if (!Stream_CheckAndLogRequiredLengthWLog(clear->log, s, residualByteCount))
392 return FALSE;
393
394 suboffset = 0;
395 pixelIndex = 0;
396 pixelCount = nWidth * nHeight;
397
398 if (!clear_resize_buffer(clear, nWidth, nHeight))
399 return FALSE;
400
401 dstBuffer = clear->TempBuffer;
402
403 while (suboffset < residualByteCount)
404 {
405 BYTE r = 0;
406 BYTE g = 0;
407 BYTE b = 0;
408 UINT32 runLengthFactor = 0;
409 UINT32 color = 0;
410
411 if (!Stream_CheckAndLogRequiredLengthWLog(clear->log, s, 4))
412 return FALSE;
413
414 Stream_Read_UINT8(s, b);
415 Stream_Read_UINT8(s, g);
416 Stream_Read_UINT8(s, r);
417 Stream_Read_UINT8(s, runLengthFactor);
418 suboffset += 4;
419 color = FreeRDPGetColor(clear->format, r, g, b, 0xFF);
420
421 if (runLengthFactor >= 0xFF)
422 {
423 if (!Stream_CheckAndLogRequiredLengthWLog(clear->log, s, 2))
424 return FALSE;
425
426 Stream_Read_UINT16(s, runLengthFactor);
427 suboffset += 2;
428
429 if (runLengthFactor >= 0xFFFF)
430 {
431 if (!Stream_CheckAndLogRequiredLengthWLog(clear->log, s, 4))
432 return FALSE;
433
434 Stream_Read_UINT32(s, runLengthFactor);
435 suboffset += 4;
436 }
437 }
438
439 if ((pixelIndex >= pixelCount) || (runLengthFactor > (pixelCount - pixelIndex)))
440 {
441 WLog_Print(clear->log, WLOG_ERROR,
442 "pixelIndex %" PRIu32 " + runLengthFactor %" PRIu32 " > pixelCount %" PRIu32
443 "",
444 pixelIndex, runLengthFactor, pixelCount);
445 return FALSE;
446 }
447
448 for (UINT32 i = 0; i < runLengthFactor; i++)
449 {
450 FreeRDPWriteColor(dstBuffer, clear->format, color);
451 dstBuffer += FreeRDPGetBytesPerPixel(clear->format);
452 }
453
454 pixelIndex += runLengthFactor;
455 }
456
457 nSrcStep = nWidth * FreeRDPGetBytesPerPixel(clear->format);
458
459 if (pixelIndex != pixelCount)
460 {
461 WLog_Print(clear->log, WLOG_ERROR, "pixelIndex %" PRIu32 " != pixelCount %" PRIu32 "",
462 pixelIndex, pixelCount);
463 return FALSE;
464 }
465
466 return convert_color(pDstData, nDstStep, DstFormat, nXDst, nYDst, nWidth, nHeight,
467 clear->TempBuffer, nSrcStep, clear->format, nDstWidth, nDstHeight,
468 palette);
469}
470
471static BOOL clear_decompress_subcodecs_data(CLEAR_CONTEXT* WINPR_RESTRICT clear,
472 wStream* WINPR_RESTRICT s, UINT32 subcodecByteCount,
473 UINT32 nWidth, UINT32 nHeight,
474 BYTE* WINPR_RESTRICT pDstData, UINT32 DstFormat,
475 UINT32 nDstStep, UINT32 nXDst, UINT32 nYDst,
476 UINT32 nDstWidth, UINT32 nDstHeight,
477 const gdiPalette* WINPR_RESTRICT palette)
478{
479 UINT32 suboffset = 0;
480
481 if (!Stream_CheckAndLogRequiredLengthWLog(clear->log, s, subcodecByteCount))
482 return FALSE;
483
484 while (suboffset < subcodecByteCount)
485 {
486 if (!Stream_CheckAndLogRequiredLengthWLog(clear->log, s, 13))
487 return FALSE;
488
489 const UINT16 xStart = Stream_Get_UINT16(s);
490 const UINT16 yStart = Stream_Get_UINT16(s);
491 const UINT16 width = Stream_Get_UINT16(s);
492 const UINT16 height = Stream_Get_UINT16(s);
493 const UINT32 bitmapDataByteCount = Stream_Get_UINT32(s);
494 const UINT8 subcodecId = Stream_Get_UINT8(s);
495 suboffset += 13;
496
497 if (!Stream_CheckAndLogRequiredLengthWLog(clear->log, s, bitmapDataByteCount))
498 return FALSE;
499
500 const UINT32 nXDstRel = nXDst + xStart;
501 const UINT32 nYDstRel = nYDst + yStart;
502 if (1ull * nXDstRel + width > nDstWidth)
503 {
504 WLog_Print(clear->log, WLOG_ERROR,
505 "nXDstRel %" PRIu32 " + width %" PRIu16 " > nDstWidth %" PRIu32 "", nXDstRel,
506 width, nDstWidth);
507 return FALSE;
508 }
509 if (1ull * nYDstRel + height > nDstHeight)
510 {
511 WLog_Print(clear->log, WLOG_ERROR,
512 "nYDstRel %" PRIu32 " + height %" PRIu16 " > nDstHeight %" PRIu32 "",
513 nYDstRel, height, nDstHeight);
514 return FALSE;
515 }
516
517 if (1ull * xStart + width > nWidth)
518 {
519 WLog_Print(clear->log, WLOG_ERROR,
520 "xStart %" PRIu16 " + width %" PRIu16 " > nWidth %" PRIu32 "", xStart, width,
521 nWidth);
522 return FALSE;
523 }
524 if (1ull * yStart + height > nHeight)
525 {
526 WLog_Print(clear->log, WLOG_ERROR,
527 "yStart %" PRIu16 " + height %" PRIu16 " > nHeight %" PRIu32 "", yStart,
528 height, nHeight);
529 return FALSE;
530 }
531
532 if (!clear_resize_buffer(clear, width, height))
533 return FALSE;
534
535 switch (subcodecId)
536 {
537 case 0: /* Uncompressed */
538 {
539 const UINT32 nSrcStep = width * FreeRDPGetBytesPerPixel(PIXEL_FORMAT_BGR24);
540 const size_t nSrcSize = 1ull * nSrcStep * height;
541
542 if (bitmapDataByteCount != nSrcSize)
543 {
544 WLog_Print(clear->log, WLOG_ERROR,
545 "bitmapDataByteCount %" PRIu32 " != nSrcSize %" PRIuz "",
546 bitmapDataByteCount, nSrcSize);
547 return FALSE;
548 }
549
550 if (!convert_color(pDstData, nDstStep, DstFormat, nXDstRel, nYDstRel, width, height,
551 Stream_Pointer(s), nSrcStep, PIXEL_FORMAT_BGR24, nDstWidth,
552 nDstHeight, palette))
553 return FALSE;
554
555 Stream_Seek(s, bitmapDataByteCount);
556 }
557 break;
558
559 case 1: /* NSCodec */
560 if (!clear_decompress_nscodec(clear->log, clear->nsc, width, height, s,
561 bitmapDataByteCount, pDstData, DstFormat, nDstStep,
562 nXDstRel, nYDstRel, nDstWidth, nDstHeight))
563 return FALSE;
564
565 break;
566
567 case 2: /* CLEARCODEC_SUBCODEC_RLEX */
568 if (!clear_decompress_subcode_rlex(clear->log, s, bitmapDataByteCount, width,
569 height, pDstData, DstFormat, nDstStep, nXDstRel,
570 nYDstRel, nDstWidth, nDstHeight))
571 return FALSE;
572
573 break;
574
575 default:
576 WLog_Print(clear->log, WLOG_ERROR, "Unknown subcodec ID %" PRIu8 "", subcodecId);
577 return FALSE;
578 }
579
580 suboffset += bitmapDataByteCount;
581 }
582
583 return TRUE;
584}
585
586static BOOL resize_vbar_entry(CLEAR_CONTEXT* WINPR_RESTRICT clear,
587 CLEAR_VBAR_ENTRY* WINPR_RESTRICT vBarEntry, UINT32 bpp)
588{
589 if (vBarEntry->count > vBarEntry->size)
590 {
591 const UINT32 oldPos = vBarEntry->size * bpp;
592 const UINT32 diffSize = (vBarEntry->count - vBarEntry->size) * bpp;
593
594 BYTE* tmp =
595 (BYTE*)winpr_aligned_recalloc(vBarEntry->pixels, vBarEntry->count, 1ull * bpp, 32);
596
597 if (!tmp)
598 {
599 WLog_Print(clear->log, WLOG_ERROR,
600 "vBarEntry->pixels winpr_aligned_recalloc %" PRIu32 " failed",
601 vBarEntry->count * bpp);
602 return FALSE;
603 }
604
605 memset(&tmp[oldPos], 0, diffSize);
606 vBarEntry->pixels = tmp;
607 vBarEntry->size = vBarEntry->count;
608 }
609
610 if (!vBarEntry->pixels && vBarEntry->size)
611 {
612 WLog_Print(clear->log, WLOG_ERROR,
613 "vBarEntry->pixels is nullptr but vBarEntry->size is %" PRIu32 "",
614 vBarEntry->size);
615 return FALSE;
616 }
617
618 return TRUE;
619}
620
621static BOOL clear_decompress_bands_data(CLEAR_CONTEXT* WINPR_RESTRICT clear,
622 wStream* WINPR_RESTRICT s, UINT32 bandsByteCount,
623 UINT32 nWidth, UINT32 nHeight,
624 BYTE* WINPR_RESTRICT pDstData, UINT32 DstFormat,
625 UINT32 nDstStep, UINT32 nXDst, UINT32 nYDst,
626 UINT32 nDstWidth, UINT32 nDstHeight)
627{
628 UINT32 suboffset = 0;
629
630 if (!Stream_CheckAndLogRequiredLengthWLog(clear->log, s, bandsByteCount))
631 return FALSE;
632
633 while (suboffset < bandsByteCount)
634 {
635 BYTE cr = 0;
636 BYTE cg = 0;
637 BYTE cb = 0;
638 UINT16 xStart = 0;
639 UINT16 xEnd = 0;
640 UINT16 yStart = 0;
641 UINT16 yEnd = 0;
642 UINT32 colorBkg = 0;
643 UINT16 vBarHeader = 0;
644 UINT16 vBarYOn = 0;
645 UINT16 vBarYOff = 0;
646 UINT32 vBarCount = 0;
647 UINT32 vBarPixelCount = 0;
648 UINT32 vBarShortPixelCount = 0;
649
650 if (!Stream_CheckAndLogRequiredLengthWLog(clear->log, s, 11))
651 return FALSE;
652
653 Stream_Read_UINT16(s, xStart);
654 Stream_Read_UINT16(s, xEnd);
655 Stream_Read_UINT16(s, yStart);
656 Stream_Read_UINT16(s, yEnd);
657 Stream_Read_UINT8(s, cb);
658 Stream_Read_UINT8(s, cg);
659 Stream_Read_UINT8(s, cr);
660 suboffset += 11;
661 colorBkg = FreeRDPGetColor(clear->format, cr, cg, cb, 0xFF);
662
663 if (xEnd < xStart)
664 {
665 WLog_Print(clear->log, WLOG_ERROR, "xEnd %" PRIu16 " < xStart %" PRIu16 "", xEnd,
666 xStart);
667 return FALSE;
668 }
669
670 if (yEnd < yStart)
671 {
672 WLog_Print(clear->log, WLOG_ERROR, "yEnd %" PRIu16 " < yStart %" PRIu16 "", yEnd,
673 yStart);
674 return FALSE;
675 }
676
677 vBarCount = (xEnd - xStart) + 1;
678
679 for (UINT32 i = 0; i < vBarCount; i++)
680 {
681 UINT32 vBarHeight = 0;
682 CLEAR_VBAR_ENTRY* vBarEntry = nullptr;
683 CLEAR_VBAR_ENTRY* vBarShortEntry = nullptr;
684 BOOL vBarUpdate = FALSE;
685 const BYTE* cpSrcPixel = nullptr;
686
687 if (!Stream_CheckAndLogRequiredLengthWLog(clear->log, s, 2))
688 return FALSE;
689
690 Stream_Read_UINT16(s, vBarHeader);
691 suboffset += 2;
692 vBarHeight = (yEnd - yStart + 1);
693
694 if (vBarHeight > 52)
695 {
696 WLog_Print(clear->log, WLOG_ERROR, "vBarHeight (%" PRIu32 ") > 52", vBarHeight);
697 return FALSE;
698 }
699
700 if ((vBarHeader & 0xC000) == 0x4000) /* SHORT_VBAR_CACHE_HIT */
701 {
702 const UINT16 vBarIndex = (vBarHeader & 0x3FFF);
703 vBarShortEntry = &(clear->ShortVBarStorage[vBarIndex]);
704
705 if (!vBarShortEntry)
706 {
707 WLog_Print(clear->log, WLOG_ERROR, "missing vBarShortEntry %" PRIu16 "",
708 vBarIndex);
709 return FALSE;
710 }
711
712 if (!Stream_CheckAndLogRequiredLengthWLog(clear->log, s, 1))
713 return FALSE;
714
715 Stream_Read_UINT8(s, vBarYOn);
716 suboffset += 1;
717 vBarShortPixelCount = vBarShortEntry->count;
718 vBarUpdate = TRUE;
719 }
720 else if ((vBarHeader & 0xC000) == 0x0000) /* SHORT_VBAR_CACHE_MISS */
721 {
722 vBarYOn = (vBarHeader & 0xFF);
723 vBarYOff = ((vBarHeader >> 8) & 0x3F);
724
725 if (vBarYOff < vBarYOn)
726 {
727 WLog_Print(clear->log, WLOG_ERROR, "vBarYOff %" PRIu16 " < vBarYOn %" PRIu16 "",
728 vBarYOff, vBarYOn);
729 return FALSE;
730 }
731
732 vBarShortPixelCount = (vBarYOff - vBarYOn);
733
734 if (vBarShortPixelCount > 52)
735 {
736 WLog_Print(clear->log, WLOG_ERROR, "vBarShortPixelCount %" PRIu32 " > 52",
737 vBarShortPixelCount);
738 return FALSE;
739 }
740
741 if (!Stream_CheckAndLogRequiredLengthOfSizeWLog(clear->log, s, vBarShortPixelCount,
742 3ull))
743 return FALSE;
744
745 if (clear->ShortVBarStorageCursor >= CLEARCODEC_VBAR_SHORT_SIZE)
746 {
747 WLog_Print(clear->log, WLOG_ERROR,
748 "clear->ShortVBarStorageCursor %" PRIu32
749 " >= CLEARCODEC_VBAR_SHORT_SIZE (%" PRId32 ")",
750 clear->ShortVBarStorageCursor, CLEARCODEC_VBAR_SHORT_SIZE);
751 return FALSE;
752 }
753
754 vBarShortEntry = &(clear->ShortVBarStorage[clear->ShortVBarStorageCursor]);
755 vBarShortEntry->count = vBarShortPixelCount;
756
757 if (!resize_vbar_entry(clear, vBarShortEntry,
758 FreeRDPGetBytesPerPixel(clear->format)))
759 return FALSE;
760
761 for (size_t y = 0; y < vBarShortPixelCount; y++)
762 {
763 BYTE r = 0;
764 BYTE g = 0;
765 BYTE b = 0;
766 BYTE* dstBuffer =
767 &vBarShortEntry->pixels[y * FreeRDPGetBytesPerPixel(clear->format)];
768 UINT32 color = 0;
769 Stream_Read_UINT8(s, b);
770 Stream_Read_UINT8(s, g);
771 Stream_Read_UINT8(s, r);
772 color = FreeRDPGetColor(clear->format, r, g, b, 0xFF);
773
774 if (!FreeRDPWriteColor(dstBuffer, clear->format, color))
775 return FALSE;
776 }
777
778 suboffset += (vBarShortPixelCount * 3);
779 clear->ShortVBarStorageCursor =
780 (clear->ShortVBarStorageCursor + 1) % CLEARCODEC_VBAR_SHORT_SIZE;
781 vBarUpdate = TRUE;
782 }
783 else if ((vBarHeader & 0x8000) == 0x8000) /* VBAR_CACHE_HIT */
784 {
785 const UINT16 vBarIndex = (vBarHeader & 0x7FFF);
786 vBarEntry = &(clear->VBarStorage[vBarIndex]);
787
788 /* If the cache was reset we need to fill in some dummy data. */
789 if (vBarEntry->size == 0)
790 {
791 WLog_Print(clear->log, WLOG_WARN,
792 "Empty cache index %" PRIu16 ", filling dummy data", vBarIndex);
793 vBarEntry->count = vBarHeight;
794
795 if (!resize_vbar_entry(clear, vBarEntry,
796 FreeRDPGetBytesPerPixel(clear->format)))
797 return FALSE;
798 }
799 }
800 else
801 {
802 WLog_Print(clear->log, WLOG_ERROR, "invalid vBarHeader 0x%04" PRIX16 "",
803 vBarHeader);
804 return FALSE; /* invalid vBarHeader */
805 }
806
807 if (vBarUpdate)
808 {
809 BYTE* pSrcPixel = nullptr;
810 BYTE* dstBuffer = nullptr;
811
812 if (clear->VBarStorageCursor >= CLEARCODEC_VBAR_SIZE)
813 {
814 WLog_Print(clear->log, WLOG_ERROR,
815 "clear->VBarStorageCursor %" PRIu32
816 " >= CLEARCODEC_VBAR_SIZE %" PRId32 "",
817 clear->VBarStorageCursor, CLEARCODEC_VBAR_SIZE);
818 return FALSE;
819 }
820
821 vBarEntry = &(clear->VBarStorage[clear->VBarStorageCursor]);
822 vBarPixelCount = vBarHeight;
823 vBarEntry->count = vBarPixelCount;
824
825 if (!resize_vbar_entry(clear, vBarEntry, FreeRDPGetBytesPerPixel(clear->format)))
826 return FALSE;
827
828 dstBuffer = vBarEntry->pixels;
829 /* if (y < vBarYOn), use colorBkg */
830 UINT32 y = 0;
831 UINT32 count = vBarYOn;
832
833 if ((y + count) > vBarPixelCount)
834 count = (vBarPixelCount > y) ? (vBarPixelCount - y) : 0;
835
836 if (count > 0)
837 {
838 while (count--)
839 {
840 FreeRDPWriteColor(dstBuffer, clear->format, colorBkg);
841 dstBuffer += FreeRDPGetBytesPerPixel(clear->format);
842 }
843 }
844
845 /*
846 * if ((y >= vBarYOn) && (y < (vBarYOn + vBarShortPixelCount))),
847 * use vBarShortPixels at index (y - shortVBarYOn)
848 */
849 y = vBarYOn;
850 count = vBarShortPixelCount;
851
852 if ((y + count) > vBarPixelCount)
853 count = (vBarPixelCount > y) ? (vBarPixelCount - y) : 0;
854
855 if (count > 0)
856 {
857 const size_t offset =
858 (1ull * y - vBarYOn) * FreeRDPGetBytesPerPixel(clear->format);
859 pSrcPixel = &vBarShortEntry->pixels[offset];
860 if (offset + count > vBarShortEntry->count)
861 {
862 WLog_Print(clear->log, WLOG_ERROR,
863 "offset + count > vBarShortEntry->count");
864 return FALSE;
865 }
866 }
867 for (size_t x = 0; x < count; x++)
868 {
869 UINT32 color = 0;
870 color = FreeRDPReadColor(&pSrcPixel[x * FreeRDPGetBytesPerPixel(clear->format)],
871 clear->format);
872
873 if (!FreeRDPWriteColor(dstBuffer, clear->format, color))
874 return FALSE;
875
876 dstBuffer += FreeRDPGetBytesPerPixel(clear->format);
877 }
878
879 /* if (y >= (vBarYOn + vBarShortPixelCount)), use colorBkg */
880 y = vBarYOn + vBarShortPixelCount;
881 count = (vBarPixelCount > y) ? (vBarPixelCount - y) : 0;
882
883 if (count > 0)
884 {
885 while (count--)
886 {
887 if (!FreeRDPWriteColor(dstBuffer, clear->format, colorBkg))
888 return FALSE;
889
890 dstBuffer += FreeRDPGetBytesPerPixel(clear->format);
891 }
892 }
893
894 vBarEntry->count = vBarPixelCount;
895 clear->VBarStorageCursor = (clear->VBarStorageCursor + 1) % CLEARCODEC_VBAR_SIZE;
896 }
897
898 if (vBarEntry->count != vBarHeight)
899 {
900 WLog_Print(clear->log, WLOG_ERROR,
901 "vBarEntry->count %" PRIu32 " != vBarHeight %" PRIu32 "",
902 vBarEntry->count, vBarHeight);
903 vBarEntry->count = vBarHeight;
904
905 if (!resize_vbar_entry(clear, vBarEntry, FreeRDPGetBytesPerPixel(clear->format)))
906 return FALSE;
907 }
908
909 const UINT32 nXDstRel = nXDst + xStart;
910 const UINT32 nYDstRel = nYDst + yStart;
911 cpSrcPixel = vBarEntry->pixels;
912
913 if (i < nWidth)
914 {
915 UINT32 count = vBarEntry->count;
916
917 if (count > nHeight)
918 count = nHeight;
919
920 if (nXDstRel + i >= nDstWidth)
921 return FALSE;
922
923 for (UINT32 y = 0; y < count; y++)
924 {
925 if (nYDstRel + y >= nDstHeight)
926 return FALSE;
927
928 BYTE* pDstPixel8 =
929 &pDstData[((nYDstRel + y) * nDstStep) +
930 ((nXDstRel + i) * FreeRDPGetBytesPerPixel(DstFormat))];
931 UINT32 color = FreeRDPReadColor(cpSrcPixel, clear->format);
932 color = FreeRDPConvertColor(color, clear->format, DstFormat, nullptr);
933
934 if (!FreeRDPWriteColor(pDstPixel8, DstFormat, color))
935 return FALSE;
936
937 cpSrcPixel += FreeRDPGetBytesPerPixel(clear->format);
938 }
939 }
940 }
941 }
942
943 return TRUE;
944}
945
946static BOOL clear_decompress_glyph_data(CLEAR_CONTEXT* WINPR_RESTRICT clear,
947 wStream* WINPR_RESTRICT s, UINT32 glyphFlags, UINT32 nWidth,
948 UINT32 nHeight, BYTE* WINPR_RESTRICT pDstData,
949 UINT32 DstFormat, UINT32 nDstStep, UINT32 nXDst,
950 UINT32 nYDst, UINT32 nDstWidth, UINT32 nDstHeight,
951 const gdiPalette* WINPR_RESTRICT palette,
952 BYTE** WINPR_RESTRICT ppGlyphData)
953{
954 UINT16 glyphIndex = 0;
955
956 if (ppGlyphData)
957 *ppGlyphData = nullptr;
958
959 if ((glyphFlags & CLEARCODEC_FLAG_GLYPH_HIT) && !(glyphFlags & CLEARCODEC_FLAG_GLYPH_INDEX))
960 {
961 WLog_Print(clear->log, WLOG_ERROR, "Invalid glyph flags %08" PRIX32 "", glyphFlags);
962 return FALSE;
963 }
964
965 if ((glyphFlags & CLEARCODEC_FLAG_GLYPH_INDEX) == 0)
966 return TRUE;
967
968 if ((nWidth * nHeight) > (1024 * 1024))
969 {
970 WLog_Print(clear->log, WLOG_ERROR, "glyph too large: %" PRIu32 "x%" PRIu32 "", nWidth,
971 nHeight);
972 return FALSE;
973 }
974
975 if (!Stream_CheckAndLogRequiredLengthWLog(clear->log, s, 2))
976 return FALSE;
977
978 Stream_Read_UINT16(s, glyphIndex);
979
980 if (glyphIndex >= 4000)
981 {
982 WLog_Print(clear->log, WLOG_ERROR, "Invalid glyphIndex %" PRIu16 "", glyphIndex);
983 return FALSE;
984 }
985
986 if (glyphFlags & CLEARCODEC_FLAG_GLYPH_HIT)
987 {
988 UINT32 nSrcStep = 0;
989 CLEAR_GLYPH_ENTRY* glyphEntry = &(clear->GlyphCache[glyphIndex]);
990 BYTE* glyphData = nullptr;
991
992 if (!glyphEntry)
993 {
994 WLog_Print(clear->log, WLOG_ERROR, "clear->GlyphCache[%" PRIu16 "]=nullptr",
995 glyphIndex);
996 return FALSE;
997 }
998
999 glyphData = (BYTE*)glyphEntry->pixels;
1000
1001 if (!glyphData)
1002 {
1003 WLog_Print(clear->log, WLOG_ERROR, "clear->GlyphCache[%" PRIu16 "]->pixels=nullptr",
1004 glyphIndex);
1005 return FALSE;
1006 }
1007
1008 if ((nWidth * nHeight) > glyphEntry->count)
1009 {
1010 WLog_Print(clear->log, WLOG_ERROR,
1011 "(nWidth %" PRIu32 " * nHeight %" PRIu32 ") > glyphEntry->count %" PRIu32 "",
1012 nWidth, nHeight, glyphEntry->count);
1013 return FALSE;
1014 }
1015
1016 nSrcStep = nWidth * FreeRDPGetBytesPerPixel(clear->format);
1017 return convert_color(pDstData, nDstStep, DstFormat, nXDst, nYDst, nWidth, nHeight,
1018 glyphData, nSrcStep, clear->format, nDstWidth, nDstHeight, palette);
1019 }
1020
1021 if (glyphFlags & CLEARCODEC_FLAG_GLYPH_INDEX)
1022 {
1023 const UINT32 bpp = FreeRDPGetBytesPerPixel(clear->format);
1024 CLEAR_GLYPH_ENTRY* glyphEntry = &(clear->GlyphCache[glyphIndex]);
1025 const size_t count = 1ull * nWidth * nHeight;
1026 const size_t hlimit = SIZE_MAX / ((nWidth > 0) ? nWidth : 1);
1027 if ((nWidth == 0) || (nHeight == 0) || (hlimit < nHeight))
1028 {
1029 const char* exceeded = (hlimit < nHeight) ? "within" : "outside";
1030 WLog_Print(clear->log, WLOG_ERROR,
1031 "CLEARCODEC_FLAG_GLYPH_INDEX: nWidth=%" PRIu32 ", nHeight=%" PRIu32
1032 ", nWidth * nHeight is %s allowed range",
1033 nWidth, nHeight, exceeded);
1034 return FALSE;
1035 }
1036
1037 if (count > glyphEntry->size)
1038 {
1039 BYTE* tmp = winpr_aligned_recalloc(glyphEntry->pixels, count, 1ull * bpp, 32);
1040
1041 if (!tmp)
1042 {
1043 WLog_Print(clear->log, WLOG_ERROR,
1044 "glyphEntry->pixels winpr_aligned_recalloc %" PRIuz " failed!",
1045 count * bpp);
1046 return FALSE;
1047 }
1048
1049 glyphEntry->count = WINPR_ASSERTING_INT_CAST(UINT32, count);
1050 glyphEntry->size = glyphEntry->count;
1051 glyphEntry->pixels = WINPR_PACKED_ALIGN_CAST(UINT32*, tmp);
1052 }
1053
1054 if (!glyphEntry->pixels)
1055 {
1056 WLog_Print(clear->log, WLOG_ERROR, "glyphEntry->pixels=nullptr");
1057 return FALSE;
1058 }
1059
1060 if (ppGlyphData)
1061 *ppGlyphData = (BYTE*)glyphEntry->pixels;
1062
1063 return TRUE;
1064 }
1065
1066 return TRUE;
1067}
1068
1069static inline BOOL updateContextFormat(CLEAR_CONTEXT* WINPR_RESTRICT clear, UINT32 DstFormat,
1070 BOOL fromNew)
1071{
1072 if (!clear || !clear->nsc)
1073 return FALSE;
1074
1075 if (!fromNew)
1076 {
1077 if (clear->formatSet)
1078 {
1079 if (!FreeRDPAreColorFormatsEqualNoAlpha(clear->format, DstFormat))
1080 {
1081 WLog_Print(
1082 clear->log, WLOG_ERROR,
1083 "Color format changed from %s to %s during decompression calls, usage error!",
1084 FreeRDPGetColorFormatName(clear->format), FreeRDPGetColorFormatName(DstFormat));
1085 return FALSE;
1086 }
1087 }
1088 else
1089 clear->formatSet = TRUE;
1090 }
1091 clear->format = DstFormat;
1092 return nsc_context_set_parameters(clear->nsc, NSC_COLOR_FORMAT, DstFormat);
1093}
1094
1095INT32 clear_decompress(CLEAR_CONTEXT* WINPR_RESTRICT clear, const BYTE* WINPR_RESTRICT pSrcData,
1096 UINT32 SrcSize, UINT32 nWidth, UINT32 nHeight, BYTE* WINPR_RESTRICT pDstData,
1097 UINT32 DstFormat, UINT32 nDstStep, UINT32 nXDst, UINT32 nYDst,
1098 UINT32 nDstWidth, UINT32 nDstHeight,
1099 const gdiPalette* WINPR_RESTRICT palette)
1100{
1101 INT32 rc = -1;
1102 BYTE seqNumber = 0;
1103 BYTE glyphFlags = 0;
1104 UINT32 residualByteCount = 0;
1105 UINT32 bandsByteCount = 0;
1106 UINT32 subcodecByteCount = 0;
1107 wStream sbuffer = WINPR_C_ARRAY_INIT;
1108 BYTE* glyphData = nullptr;
1109
1110 if (!pDstData)
1111 return -1002;
1112
1113 if ((nDstWidth == 0) || (nDstHeight == 0))
1114 return -1022;
1115
1116 if ((nWidth > 0xFFFF) || (nHeight > 0xFFFF))
1117 return -1004;
1118
1119 if (nXDst > nDstWidth)
1120 {
1121 WLog_Print(clear->log, WLOG_WARN, "nXDst %" PRIu32 " > nDstWidth %" PRIu32, nXDst,
1122 nDstWidth);
1123 return -1005;
1124 }
1125
1126 if (nYDst > nDstHeight)
1127 {
1128 WLog_Print(clear->log, WLOG_WARN, "nYDst %" PRIu32 " > nDstHeight %" PRIu32, nYDst,
1129 nDstHeight);
1130 return -1006;
1131 }
1132
1133 wStream* s = Stream_StaticConstInit(&sbuffer, pSrcData, SrcSize);
1134
1135 if (!s)
1136 return -2005;
1137
1138 if (!Stream_CheckAndLogRequiredLengthWLog(clear->log, s, 2))
1139 goto fail;
1140
1141 if (!updateContextFormat(clear, DstFormat, FALSE))
1142 goto fail;
1143
1144 Stream_Read_UINT8(s, glyphFlags);
1145 Stream_Read_UINT8(s, seqNumber);
1146
1147 if (!clear->seqNumber && seqNumber)
1148 clear->seqNumber = seqNumber;
1149
1150 if (seqNumber != clear->seqNumber)
1151 {
1152 WLog_Print(clear->log, WLOG_ERROR, "Sequence number unexpected %" PRIu8 " - %" PRIu32 "",
1153 seqNumber, clear->seqNumber);
1154 WLog_Print(clear->log, WLOG_ERROR, "seqNumber %" PRIu8 " != clear->seqNumber %" PRIu32 "",
1155 seqNumber, clear->seqNumber);
1156 goto fail;
1157 }
1158
1159 clear->seqNumber = (seqNumber + 1) % 256;
1160
1161 if (glyphFlags & CLEARCODEC_FLAG_CACHE_RESET)
1162 {
1163 clear_reset_vbar_storage(clear, FALSE);
1164 }
1165
1166 if (!clear_decompress_glyph_data(clear, s, glyphFlags, nWidth, nHeight, pDstData, DstFormat,
1167 nDstStep, nXDst, nYDst, nDstWidth, nDstHeight, palette,
1168 &glyphData))
1169 {
1170 WLog_Print(clear->log, WLOG_ERROR, "clear_decompress_glyph_data failed!");
1171 goto fail;
1172 }
1173
1174 /* Read composition payload header parameters */
1175 if (Stream_GetRemainingLength(s) < 12)
1176 {
1177 const UINT32 mask = (CLEARCODEC_FLAG_GLYPH_HIT | CLEARCODEC_FLAG_GLYPH_INDEX);
1178
1179 if ((glyphFlags & mask) == mask)
1180 goto finish;
1181
1182 WLog_Print(clear->log, WLOG_ERROR,
1183 "invalid glyphFlags, missing flags: 0x%02" PRIx8 " & 0x%02" PRIx32
1184 " == 0x%02" PRIx32,
1185 glyphFlags, mask, glyphFlags & mask);
1186 goto fail;
1187 }
1188
1189 Stream_Read_UINT32(s, residualByteCount);
1190 Stream_Read_UINT32(s, bandsByteCount);
1191 Stream_Read_UINT32(s, subcodecByteCount);
1192
1193 if (residualByteCount > 0)
1194 {
1195 if (!clear_decompress_residual_data(clear, s, residualByteCount, nWidth, nHeight, pDstData,
1196 DstFormat, nDstStep, nXDst, nYDst, nDstWidth,
1197 nDstHeight, palette))
1198 {
1199 WLog_Print(clear->log, WLOG_ERROR, "clear_decompress_residual_data failed!");
1200 goto fail;
1201 }
1202 }
1203
1204 if (bandsByteCount > 0)
1205 {
1206 if (!clear_decompress_bands_data(clear, s, bandsByteCount, nWidth, nHeight, pDstData,
1207 DstFormat, nDstStep, nXDst, nYDst, nDstWidth, nDstHeight))
1208 {
1209 WLog_Print(clear->log, WLOG_ERROR, "clear_decompress_bands_data failed!");
1210 goto fail;
1211 }
1212 }
1213
1214 if (subcodecByteCount > 0)
1215 {
1216 if (!clear_decompress_subcodecs_data(clear, s, subcodecByteCount, nWidth, nHeight, pDstData,
1217 DstFormat, nDstStep, nXDst, nYDst, nDstWidth,
1218 nDstHeight, palette))
1219 {
1220 WLog_Print(clear->log, WLOG_ERROR, "clear_decompress_subcodecs_data failed!");
1221 goto fail;
1222 }
1223 }
1224
1225 if (glyphData)
1226 {
1227 uint32_t w = MIN(nWidth, nDstWidth);
1228 if (nXDst > nDstWidth)
1229 {
1230 WLog_Print(clear->log, WLOG_WARN,
1231 "glyphData copy area x exceeds destination: x=%" PRIu32 " > %" PRIu32, nXDst,
1232 nDstWidth);
1233 w = 0;
1234 }
1235 else if (nXDst + w > nDstWidth)
1236 {
1237 WLog_Print(clear->log, WLOG_WARN,
1238 "glyphData copy area x + width exceeds destination: x=%" PRIu32 " + %" PRIu32
1239 " > %" PRIu32,
1240 nXDst, w, nDstWidth);
1241 w = nDstWidth - nXDst;
1242 }
1243
1244 if (w != nWidth)
1245 {
1246 WLog_Print(clear->log, WLOG_WARN,
1247 "glyphData copy area width truncated: requested=%" PRIu32
1248 ", truncated to %" PRIu32,
1249 nWidth, w);
1250 }
1251
1252 uint32_t h = MIN(nHeight, nDstHeight);
1253 if (nYDst > nDstHeight)
1254 {
1255 WLog_Print(clear->log, WLOG_WARN,
1256 "glyphData copy area y exceeds destination: y=%" PRIu32 " > %" PRIu32, nYDst,
1257 nDstHeight);
1258 h = 0;
1259 }
1260 else if (nYDst + h > nDstHeight)
1261 {
1262 WLog_Print(clear->log, WLOG_WARN,
1263 "glyphData copy area y + height exceeds destination: x=%" PRIu32
1264 " + %" PRIu32 " > %" PRIu32,
1265 nYDst, h, nDstHeight);
1266 h = nDstHeight - nYDst;
1267 }
1268
1269 if (h != nHeight)
1270 {
1271 WLog_Print(clear->log, WLOG_WARN,
1272 "glyphData copy area height truncated: requested=%" PRIu32
1273 ", truncated to %" PRIu32,
1274 nHeight, h);
1275 }
1276
1277 if (!freerdp_image_copy_no_overlap(glyphData, clear->format, 0, 0, 0, w, h, pDstData,
1278 DstFormat, nDstStep, nXDst, nYDst, palette,
1279 FREERDP_KEEP_DST_ALPHA))
1280 goto fail;
1281 }
1282
1283finish:
1284 rc = 0;
1285fail:
1286 return rc;
1287}
1288
1289/* Write one CLEARCODEC_RGB_RUN_SEGMENT: BGR triplet + a 1/2/4 byte run length using the
1290 * 0xFF / 0xFFFF escape scheme mirrored from clear_decompress_residual_data(). */
1291static void clear_write_run_segment(wStream* WINPR_RESTRICT s, BYTE r, BYTE g, BYTE b,
1292 UINT32 runLength)
1293{
1294 Stream_Write_UINT8(s, b);
1295 Stream_Write_UINT8(s, g);
1296 Stream_Write_UINT8(s, r);
1297
1298 if (runLength < 0xFF)
1299 Stream_Write_UINT8(s, WINPR_ASSERTING_INT_CAST(UINT8, runLength));
1300 else if (runLength < 0xFFFF)
1301 {
1302 Stream_Write_UINT8(s, 0xFF);
1303 Stream_Write_UINT16(s, WINPR_ASSERTING_INT_CAST(UINT16, runLength));
1304 }
1305 else
1306 {
1307 Stream_Write_UINT8(s, 0xFF);
1308 Stream_Write_UINT16(s, 0xFFFF);
1309 Stream_Write_UINT32(s, runLength);
1310 }
1311}
1312
1313/* Encode the whole rectangle as a single CLEARCODEC_RESIDUAL_DATA layer: a row-major run-length
1314 * encoding of BGR pixel runs. This is always spec-valid on its own (bands/subcodec layers are
1315 * optional) */
1316static BOOL clear_compress_residual_data(CLEAR_CONTEXT* WINPR_RESTRICT clear,
1317 wStream* WINPR_RESTRICT s,
1318 const BYTE* WINPR_RESTRICT pSrcData, UINT32 SrcFormat,
1319 UINT32 nSrcStep, UINT32 nWidth, UINT32 nHeight)
1320{
1321 const UINT32 bpp = FreeRDPGetBytesPerPixel(SrcFormat);
1322 const UINT64 pixelCount = 1ull * nWidth * nHeight;
1323 /* Worst case: every pixel differs from its predecessor, i.e. one 4-byte segment per pixel. */
1324 const UINT64 requiredBytes = pixelCount * 4ull;
1325 BOOL havePending = FALSE;
1326 BYTE pr = 0;
1327 BYTE pg = 0;
1328 BYTE pb = 0;
1329 UINT32 runLength = 0;
1330
1331 if (!Stream_EnsureRemainingCapacity(s, WINPR_ASSERTING_INT_CAST(size_t, requiredBytes)))
1332 {
1333 WLog_Print(clear->log, WLOG_ERROR,
1334 "Stream_EnsureRemainingCapacity failed for %" PRIu64 " bytes", requiredBytes);
1335 return FALSE;
1336 }
1337
1338 for (UINT32 y = 0; y < nHeight; y++)
1339 {
1340 const BYTE* pSrcPixel = &pSrcData[1ull * y * nSrcStep];
1341
1342 for (UINT32 x = 0; x < nWidth; x++)
1343 {
1344 BYTE r = 0;
1345 BYTE g = 0;
1346 BYTE b = 0;
1347 BYTE a = 0;
1348 const UINT32 color = FreeRDPReadColor(pSrcPixel, SrcFormat);
1349 pSrcPixel += bpp;
1350 FreeRDPSplitColor(color, SrcFormat, &r, &g, &b, &a, nullptr);
1351
1352 if (havePending && (r == pr) && (g == pg) && (b == pb))
1353 {
1354 runLength++;
1355 continue;
1356 }
1357
1358 if (havePending)
1359 clear_write_run_segment(s, pr, pg, pb, runLength);
1360
1361 pr = r;
1362 pg = g;
1363 pb = b;
1364 runLength = 1;
1365 havePending = TRUE;
1366 }
1367 }
1368
1369 if (havePending)
1370 clear_write_run_segment(s, pr, pg, pb, runLength);
1371
1372 return TRUE;
1373}
1374
1375/* FNV-1a 64 bit, used only to pick a starting probe bucket for the encoder's V-Bar lookup
1376 * index; every candidate is still verified with a full memcmp, so collisions only cost an
1377 * extra probe, never a wrong answer. */
1378static UINT64 clear_vbar_content_hash(const BYTE* WINPR_RESTRICT data, size_t len)
1379{
1380 UINT64 hash = 0xcbf29ce484222325ull;
1381
1382 for (size_t i = 0; i < len; i++)
1383 {
1384 hash ^= data[i];
1385 hash *= 0x100000001b3ull;
1386 }
1387
1388 return hash;
1389}
1390
1391/* Find an existing clear->VBarStorage slot whose content exactly matches [data, data+count*3).
1392 * Read-only: never mutates clear->VBarStorage or the hash index. Returns the slot index, or
1393 * UINT32_MAX if no such content is currently cached. */
1394static UINT32 clear_vbar_hash_lookup(CLEAR_CONTEXT* WINPR_RESTRICT clear,
1395 const BYTE* WINPR_RESTRICT data, UINT32 count)
1396{
1397 const size_t len = 1ull * count * 3;
1398 const UINT64 hash = clear_vbar_content_hash(data, len);
1399 UINT32 i = WINPR_ASSERTING_INT_CAST(UINT32, hash & (CLEAR_VBAR_HASH_SIZE - 1));
1400
1401 for (UINT32 probe = 0; probe < CLEAR_VBAR_HASH_SIZE; probe++)
1402 {
1403 const UINT32 slot = clear->VBarHashSlots[i];
1404
1405 if (slot == CLEAR_VBAR_HASH_EMPTY)
1406 return UINT32_MAX;
1407
1408 if (slot != CLEAR_VBAR_HASH_DELETED)
1409 {
1410 const UINT32 index = slot - 1;
1411 const CLEAR_VBAR_ENTRY* entry = &clear->VBarStorage[index];
1412
1413 if ((entry->count == count) && (memcmp(entry->pixels, data, len) == 0))
1414 return index;
1415 }
1416
1417 i = (i + 1) & (CLEAR_VBAR_HASH_SIZE - 1);
1418 }
1419
1420 return UINT32_MAX;
1421}
1422
1423/* Remove whatever entry currently maps to clear->VBarStorage[index] from the hash index, based
1424 * on its CURRENT content. Must be called before that slot's content is overwritten, otherwise
1425 * the index would keep pointing a stale lookup at content that is no longer there. */
1426static void clear_vbar_hash_remove(CLEAR_CONTEXT* WINPR_RESTRICT clear, UINT32 index)
1427{
1428 const CLEAR_VBAR_ENTRY* entry = &clear->VBarStorage[index];
1429
1430 if ((entry->count == 0) || !entry->pixels)
1431 return;
1432
1433 const size_t len = 1ull * entry->count * 3;
1434 const UINT64 hash = clear_vbar_content_hash(entry->pixels, len);
1435 UINT32 i = WINPR_ASSERTING_INT_CAST(UINT32, hash & (CLEAR_VBAR_HASH_SIZE - 1));
1436
1437 for (UINT32 probe = 0; probe < CLEAR_VBAR_HASH_SIZE; probe++)
1438 {
1439 if (clear->VBarHashSlots[i] == (index + 1))
1440 {
1441 clear->VBarHashSlots[i] = CLEAR_VBAR_HASH_DELETED;
1442 return;
1443 }
1444
1445 if (clear->VBarHashSlots[i] == CLEAR_VBAR_HASH_EMPTY)
1446 return;
1447
1448 i = (i + 1) & (CLEAR_VBAR_HASH_SIZE - 1);
1449 }
1450}
1451
1452/* Index clear->VBarStorage[index] (using its current content) so future lookups can find it. */
1453static void clear_vbar_hash_insert(CLEAR_CONTEXT* WINPR_RESTRICT clear, UINT32 index)
1454{
1455 const CLEAR_VBAR_ENTRY* entry = &clear->VBarStorage[index];
1456 const size_t len = 1ull * entry->count * 3;
1457 const UINT64 hash = clear_vbar_content_hash(entry->pixels, len);
1458 UINT32 i = WINPR_ASSERTING_INT_CAST(UINT32, hash & (CLEAR_VBAR_HASH_SIZE - 1));
1459
1460 for (UINT32 probe = 0; probe < CLEAR_VBAR_HASH_SIZE; probe++)
1461 {
1462 const UINT32 slot = clear->VBarHashSlots[i];
1463
1464 if ((slot == CLEAR_VBAR_HASH_EMPTY) || (slot == CLEAR_VBAR_HASH_DELETED))
1465 {
1466 clear->VBarHashSlots[i] = index + 1;
1467 return;
1468 }
1469
1470 i = (i + 1) & (CLEAR_VBAR_HASH_SIZE - 1);
1471 }
1472}
1473
1474/* Emit a VBAR_CACHE_HIT: the decoder already has this column at clear->VBarStorage[index]. */
1475static BOOL clear_compress_write_vbar_hit(wStream* WINPR_RESTRICT s, UINT32 index)
1476{
1477 if (!Stream_EnsureRemainingCapacity(s, 2))
1478 return FALSE;
1479
1480 Stream_Write_UINT16(s, WINPR_ASSERTING_INT_CAST(UINT16, 0x8000u | index));
1481 return TRUE;
1482}
1483
1484/* Emit a SHORT_VBAR_CACHE_MISS (header + raw BGR pixels): a column never seen before. Also
1485 * mirrors clear_decompress_bands_data()'s cache update so the decoder's and encoder's V-Bar
1486 * caches stay in lockstep, keeping future VBAR_CACHE_HIT indices valid. shortVBarYOn is always
1487 * 0 here since this encoder never trims a column against the band's background color. */
1488static BOOL clear_compress_write_vbar_miss(CLEAR_CONTEXT* WINPR_RESTRICT clear,
1489 wStream* WINPR_RESTRICT s,
1490 const BYTE* WINPR_RESTRICT columnBgr, UINT32 count)
1491{
1492 if (!Stream_EnsureRemainingCapacity(s, 2ull + 1ull * count * 3))
1493 return FALSE;
1494
1495 Stream_Write_UINT16(s, WINPR_ASSERTING_INT_CAST(UINT16, count << 8)); /* yOn=0, yOff=count */
1496 Stream_Write(s, columnBgr, 1ull * count * 3);
1497
1498 const UINT32 index = clear->VBarStorageCursor;
1499 CLEAR_VBAR_ENTRY* entry = &clear->VBarStorage[index];
1500
1501 clear_vbar_hash_remove(clear, index);
1502 entry->count = count;
1503
1504 if (!resize_vbar_entry(clear, entry, 3))
1505 return FALSE;
1506
1507 CopyMemory(entry->pixels, columnBgr, 1ull * count * 3);
1508 clear_vbar_hash_insert(clear, index);
1509
1510 clear->VBarStorageCursor = (clear->VBarStorageCursor + 1) % CLEARCODEC_VBAR_SIZE;
1511 return TRUE;
1512}
1513
1514/* Encode CLEARCODEC_BANDS_DATA: fixed-height (<=52 row), full-width bands, one V-Bar per
1515 * column. Every column is cache-checked against clear->VBarStorage; unseen columns are sent
1516 * raw and added to the cache for later frames to reference. Mutates clear's V-Bar cache state,
1517 * so unlike the residual layer this cannot be spuriously discarded once written: whatever this
1518 * writes to the wire must reach the decoder, or the two caches fall out of sync. */
1519static BOOL clear_compress_bands_data(CLEAR_CONTEXT* WINPR_RESTRICT clear,
1520 wStream* WINPR_RESTRICT s,
1521 const BYTE* WINPR_RESTRICT pSrcData, UINT32 SrcFormat,
1522 UINT32 nSrcStep, UINT32 nWidth, UINT32 nHeight)
1523{
1524 const UINT32 bpp = FreeRDPGetBytesPerPixel(SrcFormat);
1525 BYTE columnBgr[1ull * CLEAR_BAND_MAX_HEIGHT * 3];
1526
1527 for (UINT32 yStart = 0; yStart < nHeight; yStart += CLEAR_BAND_MAX_HEIGHT)
1528 {
1529 const UINT32 bandHeight = MIN(CLEAR_BAND_MAX_HEIGHT, nHeight - yStart);
1530 const UINT32 yEnd = yStart + bandHeight - 1;
1531
1532 if (!Stream_EnsureRemainingCapacity(s, 11))
1533 return FALSE;
1534
1535 Stream_Write_UINT16(s, 0); /* xStart */
1536 Stream_Write_UINT16(s, WINPR_ASSERTING_INT_CAST(UINT16, nWidth - 1)); /* xEnd */
1537 Stream_Write_UINT16(s, WINPR_ASSERTING_INT_CAST(UINT16, yStart));
1538 Stream_Write_UINT16(s, WINPR_ASSERTING_INT_CAST(UINT16, yEnd));
1539 Stream_Write_UINT8(s, 0); /* blueBkg: unused, columns are never background-trimmed */
1540 Stream_Write_UINT8(s, 0); /* greenBkg */
1541 Stream_Write_UINT8(s, 0); /* redBkg */
1542
1543 for (UINT32 x = 0; x < nWidth; x++)
1544 {
1545 for (UINT32 y = 0; y < bandHeight; y++)
1546 {
1547 BYTE r = 0;
1548 BYTE g = 0;
1549 BYTE b = 0;
1550 BYTE a = 0;
1551 const BYTE* pPixel = &pSrcData[(1ull * (yStart + y)) * nSrcStep + 1ull * x * bpp];
1552 const UINT32 color = FreeRDPReadColor(pPixel, SrcFormat);
1553 FreeRDPSplitColor(color, SrcFormat, &r, &g, &b, &a, nullptr);
1554 columnBgr[y * 3 + 0] = b;
1555 columnBgr[y * 3 + 1] = g;
1556 columnBgr[y * 3 + 2] = r;
1557 }
1558
1559 const UINT32 hit = clear_vbar_hash_lookup(clear, columnBgr, bandHeight);
1560
1561 if (hit != UINT32_MAX)
1562 {
1563 if (!clear_compress_write_vbar_hit(s, hit))
1564 return FALSE;
1565 }
1566 else if (!clear_compress_write_vbar_miss(clear, s, columnBgr, bandHeight))
1567 return FALSE;
1568 }
1569 }
1570
1571 return TRUE;
1572}
1573
1574static BOOL clear_write_uint32_at(wStream* WINPR_RESTRICT s, size_t pos, UINT32 value)
1575{
1576 const size_t end = Stream_GetPosition(s);
1577 if (!Stream_SetPosition(s, pos))
1578 return FALSE;
1579 Stream_Write_UINT32(s, value);
1580 return Stream_SetPosition(s, end);
1581}
1582
1583static BOOL clear_compress_finish(CLEAR_CONTEXT* WINPR_RESTRICT clear, wStream* WINPR_RESTRICT s,
1584 BYTE** WINPR_RESTRICT ppDstData, UINT32* WINPR_RESTRICT pDstSize)
1585{
1586 clear->seqNumber = (clear->seqNumber + 1) % 256;
1587
1588 *ppDstData = Stream_Buffer(s);
1589 *pDstSize = WINPR_ASSERTING_INT_CAST(UINT32, Stream_GetPosition(s));
1590 return TRUE;
1591}
1592
1593/* Count the distinct RGB colors of the rectangle, stopping once more than maxColors are found.
1594 * Returns maxColors + 1 in that case, or UINT32_MAX on allocation failure. */
1595static UINT32 clear_count_colors(CLEAR_CONTEXT* WINPR_RESTRICT clear,
1596 const BYTE* WINPR_RESTRICT pSrcData, UINT32 SrcFormat,
1597 UINT32 nSrcStep, UINT32 nWidth, UINT32 nHeight, UINT32 maxColors)
1598{
1599 const UINT32 bpp = FreeRDPGetBytesPerPixel(SrcFormat);
1600
1601 /* a power of two, at least twice the number of colors it may hold */
1602 UINT32 bits = 6;
1603 while ((1ull << bits) < 2ull * (maxColors + 1ull))
1604 bits++;
1605 const size_t setSize = 1ull << bits;
1606
1607 if (setSize > clear->ColorSetSize)
1608 {
1609 UINT32* tmp = realloc(clear->ColorSet, setSize * sizeof(UINT32));
1610 if (!tmp)
1611 return UINT32_MAX;
1612 clear->ColorSet = tmp;
1613 clear->ColorSetSize = setSize;
1614 }
1615 ZeroMemory(clear->ColorSet, setSize * sizeof(UINT32));
1616
1617 const size_t mask = setSize - 1;
1618 UINT32 count = 0;
1619 for (UINT32 y = 0; y < nHeight; y++)
1620 {
1621 const BYTE* pLine = &pSrcData[1ull * y * nSrcStep];
1622 for (UINT32 x = 0; x < nWidth; x++)
1623 {
1624 BYTE r = 0;
1625 BYTE g = 0;
1626 BYTE b = 0;
1627 const UINT32 color = FreeRDPReadColor(&pLine[1ull * x * bpp], SrcFormat);
1628 FreeRDPSplitColor(color, SrcFormat, &r, &g, &b, nullptr, nullptr);
1629
1630 /* bit 24 set so that no color is stored as 0, the empty slot marker */
1631 const UINT32 key = 0x01000000u | ((UINT32)r << 16) | ((UINT32)g << 8) | b;
1632 size_t slot = (key * 2654435761u) >> (32 - bits);
1633
1634 UINT32 cur = clear->ColorSet[slot];
1635 while ((cur != 0) && (cur != key))
1636 {
1637 slot = (slot + 1) & mask;
1638 if (slot >= clear->ColorSetSize)
1639 return UINT32_MAX;
1640 cur = clear->ColorSet[slot];
1641 }
1642
1643 if (clear->ColorSet[slot] == 0)
1644 {
1645 clear->ColorSet[slot] = key;
1646 if (++count > maxColors)
1647 return count;
1648 }
1649 }
1650 }
1651
1652 return count;
1653}
1654
1655/* Encode the rectangle with NSCodec into clear->nscStream: color loss level 3, no chroma
1656 * subsampling, no alpha plane. */
1657static BOOL clear_compress_nscodec(CLEAR_CONTEXT* WINPR_RESTRICT clear,
1658 const BYTE* WINPR_RESTRICT pSrcData, UINT32 SrcFormat,
1659 UINT32 nSrcStep, UINT32 nWidth, UINT32 nHeight)
1660{
1661 const UINT32 nscStep = nWidth * FreeRDPGetBytesPerPixel(PIXEL_FORMAT_BGRX32);
1662
1663 /* the SSE2 NSCodec encoder reads pixels by groups of 8, up to 7 past the end of a row */
1664 const size_t size = 1ull * nscStep * nHeight + 32;
1665 if (size > clear->NscBufferSize)
1666 {
1667 BYTE* tmp = winpr_aligned_recalloc(clear->NscBuffer, size, sizeof(BYTE), 32);
1668 if (!tmp)
1669 return FALSE;
1670 clear->NscBuffer = tmp;
1671 clear->NscBufferSize = size;
1672 }
1673
1674 /* nsc_compose_message() reads the image bottom-up, the subcodec is top-down */
1675 if (!freerdp_image_copy_no_overlap(clear->NscBuffer, PIXEL_FORMAT_BGRX32, nscStep, 0, 0, nWidth,
1676 nHeight, pSrcData, SrcFormat, nSrcStep, 0, 0, nullptr,
1677 FREERDP_FLIP_VERTICAL))
1678 return FALSE;
1679
1680 if (!nsc_context_set_parameters(clear->nsc, NSC_COLOR_FORMAT, PIXEL_FORMAT_BGRX32))
1681 return FALSE;
1682
1683 Stream_ResetPosition(clear->nscStream);
1684 return nsc_compose_message(clear->nsc, clear->nscStream, clear->NscBuffer, nWidth, nHeight,
1685 nscStep);
1686}
1687
1688/* Encode the whole rectangle as a single NSCodec subcodec if it has many colors (more than 40%
1689 * of its pixels) and NSCodec beats maxSize bytes. Returns the number of bytes written to s, 0
1690 * when NSCodec is not used, or a negative value on error. */
1691static SSIZE_T clear_compress_subcodecs(CLEAR_CONTEXT* WINPR_RESTRICT clear,
1692 wStream* WINPR_RESTRICT s,
1693 const BYTE* WINPR_RESTRICT pSrcData, UINT32 SrcFormat,
1694 UINT32 nSrcStep, UINT32 nWidth, UINT32 nHeight,
1695 size_t maxSize)
1696{
1697 const UINT64 nPixels = 1ull * nWidth * nHeight;
1698
1699 /* the NSCodec stream header alone is 20 bytes */
1700 if (nPixels <= 9)
1701 return 0;
1702
1703 const UINT32 maxColors = WINPR_ASSERTING_INT_CAST(UINT32, nPixels * 2 / 5);
1704 const UINT32 colors =
1705 clear_count_colors(clear, pSrcData, SrcFormat, nSrcStep, nWidth, nHeight, maxColors);
1706 if (colors == UINT32_MAX)
1707 return -1;
1708 if (colors <= maxColors)
1709 return 0;
1710
1711 if (!clear_compress_nscodec(clear, pSrcData, SrcFormat, nSrcStep, nWidth, nHeight))
1712 return -1;
1713
1714 const size_t nscSize = Stream_GetPosition(clear->nscStream);
1715 const size_t subcodecSize = 13 + nscSize;
1716 if ((nscSize >= 3 * nPixels) || (subcodecSize >= maxSize))
1717 return 0;
1718
1719 if (!Stream_EnsureRemainingCapacity(s, subcodecSize))
1720 return -1;
1721
1722 Stream_Write_UINT16(s, 0); /* xStart */
1723 Stream_Write_UINT16(s, 0); /* yStart */
1724 Stream_Write_UINT16(s, WINPR_ASSERTING_INT_CAST(UINT16, nWidth));
1725 Stream_Write_UINT16(s, WINPR_ASSERTING_INT_CAST(UINT16, nHeight));
1726 Stream_Write_UINT32(s, WINPR_ASSERTING_INT_CAST(UINT32, nscSize)); /* bitmapDataByteCount */
1727 Stream_Write_UINT8(s, 1); /* subcodecId: NSCodec */
1728 Stream_Write(s, Stream_Buffer(clear->nscStream), nscSize);
1729 return WINPR_ASSERTING_INT_CAST(SSIZE_T, subcodecSize);
1730}
1731
1732BOOL clear_compress(CLEAR_CONTEXT* WINPR_RESTRICT clear, const BYTE* WINPR_RESTRICT pSrcData,
1733 UINT32 SrcFormat, UINT32 nSrcStep, UINT32 nWidth, UINT32 nHeight,
1734 BYTE** WINPR_RESTRICT ppDstData, UINT32* WINPR_RESTRICT pDstSize)
1735{
1736 if (!clear || !clear->Compressor || !clear->bs)
1737 return FALSE;
1738
1739 if (!pSrcData || !ppDstData || !pDstSize)
1740 return FALSE;
1741
1742 if ((nWidth == 0) || (nHeight == 0) || (nWidth > 0xFFFF) || (nHeight > 0xFFFF))
1743 return FALSE;
1744
1745 if (nSrcStep == 0)
1746 nSrcStep = nWidth * FreeRDPGetBytesPerPixel(SrcFormat);
1747
1748 wStream* s = clear->bs;
1749 if (!Stream_SetPosition(s, 0))
1750 return FALSE;
1751
1752 if (!Stream_EnsureRemainingCapacity(s, 14))
1753 return FALSE;
1754
1755 Stream_Write_UINT8(s, 0); /* glyphFlags: no glyph cache use */
1756 Stream_Write_UINT8(s, WINPR_ASSERTING_INT_CAST(UINT8, clear->seqNumber));
1757
1758 const size_t residualByteCountPos = Stream_GetPosition(s);
1759 Stream_Write_UINT32(s, 0); /* residualByteCount, backpatched below */
1760 const size_t bandsByteCountPos = Stream_GetPosition(s);
1761 Stream_Write_UINT32(s, 0); /* bandsByteCount, backpatched below */
1762 const size_t subcodecByteCountPos = Stream_GetPosition(s);
1763 Stream_Write_UINT32(s, 0); /* subcodecByteCount, backpatched below */
1764
1765 const size_t residualStart = Stream_GetPosition(s);
1766
1767 if (!clear_compress_residual_data(clear, s, pSrcData, SrcFormat, nSrcStep, nWidth, nHeight))
1768 return FALSE;
1769
1770 UINT32 residualByteCount =
1771 WINPR_ASSERTING_INT_CAST(UINT32, Stream_GetPosition(s) - residualStart);
1772
1773 /* Content with many colors is sent as a single NSCodec subcodec replacing the residual
1774 * layer, when that is smaller. The subcodec layer touches no cache. */
1775 if (!Stream_SetPosition(s, residualStart))
1776 return FALSE;
1777 const SSIZE_T subcodecByteCount = clear_compress_subcodecs(
1778 clear, s, pSrcData, SrcFormat, nSrcStep, nWidth, nHeight, residualByteCount);
1779 if (subcodecByteCount < 0)
1780 return FALSE;
1781 if (subcodecByteCount > 0)
1782 {
1783 if (!clear_write_uint32_at(s, subcodecByteCountPos,
1784 WINPR_ASSERTING_INT_CAST(UINT32, subcodecByteCount)))
1785 return FALSE;
1786 return clear_compress_finish(clear, s, ppDstData, pDstSize);
1787 }
1788 if (!Stream_SetPosition(s, residualStart + residualByteCount))
1789 return FALSE;
1790
1791 /* Bands and residual both cover 100% of the rectangle on their own (this encoder never
1792 * trims a band down to a partial region), so there is no benefit to sending both - it would
1793 * just mean the decoder redundantly redraws every pixel twice. Pick one.
1794 *
1795 * The band layer costs at least 11 header bytes per band plus 2 bytes per column (the
1796 * cheapest possible outcome, a VBAR_CACHE_HIT for every single column). If the residual
1797 * layer already beats that floor, bands cannot possibly shrink the output further, so skip
1798 * them entirely. Once that gate passes we commit to bands unconditionally rather than
1799 * comparing actual sizes afterwards: clear_compress_bands_data() mutates the V-Bar cache as
1800 * it goes (new columns are inserted so later frames can reference them), and undoing that
1801 * after the fact to fall back to residual would desync the encoder's cache from the
1802 * decoder's, which never rolls back what it has already decoded. */
1803 UINT32 bandsByteCount = 0;
1804 const UINT32 numBands = (nHeight + CLEAR_BAND_MAX_HEIGHT - 1) / CLEAR_BAND_MAX_HEIGHT;
1805 const UINT64 minBandsCost = (1ull * numBands * 11ull) + (2ull * numBands * nWidth);
1806
1807 if (clear->VBarHashSlots && (residualByteCount > minBandsCost))
1808 {
1809 if (!Stream_SetPosition(s, residualStart))
1810 return FALSE;
1811
1812 if (!clear_compress_bands_data(clear, s, pSrcData, SrcFormat, nSrcStep, nWidth, nHeight))
1813 return FALSE;
1814
1815 bandsByteCount = WINPR_ASSERTING_INT_CAST(UINT32, Stream_GetPosition(s) - residualStart);
1816 residualByteCount = 0;
1817 }
1818
1819 if (!clear_write_uint32_at(s, residualByteCountPos, residualByteCount) ||
1820 !clear_write_uint32_at(s, bandsByteCountPos, bandsByteCount))
1821 return FALSE;
1822
1823 return clear_compress_finish(clear, s, ppDstData, pDstSize);
1824}
1825
1826BOOL clear_context_reset(CLEAR_CONTEXT* WINPR_RESTRICT clear)
1827{
1828 if (!clear)
1829 return FALSE;
1830
1835 clear->seqNumber = 0;
1836 return TRUE;
1837}
1838
1839CLEAR_CONTEXT* clear_context_new(BOOL Compressor)
1840{
1841 CLEAR_CONTEXT* clear = (CLEAR_CONTEXT*)winpr_aligned_calloc(1, sizeof(CLEAR_CONTEXT), 32);
1842
1843 if (!clear)
1844 return nullptr;
1845 clear->log = WLog_Get(TAG);
1846 clear->Compressor = Compressor;
1847 clear->nsc = nsc_context_new();
1848
1849 if (!clear->nsc)
1850 goto error_nsc;
1851
1852 if (!updateContextFormat(clear, PIXEL_FORMAT_BGRX32, TRUE))
1853 goto error_nsc;
1854
1855 if (!clear_resize_buffer(clear, 512, 512))
1856 goto error_nsc;
1857
1858 if (!clear->TempBuffer)
1859 goto error_nsc;
1860
1861 if (Compressor)
1862 {
1863 clear->bs = Stream_New(nullptr, 1024);
1864 if (!clear->bs)
1865 goto error_nsc;
1866
1867 clear->nscStream = Stream_New(nullptr, 1024);
1868 if (!clear->nscStream)
1869 goto error_nsc;
1870
1871 if (!nsc_context_set_parameters(clear->nsc, NSC_COLOR_LOSS_LEVEL, 3) ||
1872 !nsc_context_set_parameters(clear->nsc, NSC_ALLOW_SUBSAMPLING, 0))
1873 goto error_nsc;
1874
1875 clear->VBarHashSlots =
1876 (UINT32*)winpr_aligned_calloc(CLEAR_VBAR_HASH_SIZE, sizeof(UINT32), 32);
1877 if (!clear->VBarHashSlots)
1878 goto error_nsc;
1879 }
1880
1881 if (!clear_context_reset(clear))
1882 goto error_nsc;
1883
1884 return clear;
1885error_nsc:
1886 WINPR_PRAGMA_DIAG_PUSH
1887 WINPR_PRAGMA_DIAG_IGNORED_MISMATCHED_DEALLOC
1888 clear_context_free(clear);
1889 WINPR_PRAGMA_DIAG_POP
1890 return nullptr;
1891}
1892
1893void clear_context_free(CLEAR_CONTEXT* WINPR_RESTRICT clear)
1894{
1895 if (!clear)
1896 return;
1897
1898 nsc_context_free(clear->nsc);
1899 winpr_aligned_free(clear->TempBuffer);
1900 Stream_Free(clear->bs, TRUE);
1901
1902 clear_reset_vbar_storage(clear, TRUE);
1903 clear_reset_glyph_cache(clear);
1904 winpr_aligned_free(clear->VBarHashSlots);
1905 winpr_aligned_free(clear->NscBuffer);
1906 Stream_Free(clear->nscStream, TRUE);
1907 free(clear->ColorSet);
1908
1909 winpr_aligned_free(clear);
1910}