view src/main/java/com/glavsoft/rfb/encoding/decoder/ZRLEDecoder.java @ 526:fcd833c2e148

Multicast Bloking in ZRLEDecoder
author riono210
date Thu, 02 May 2019 16:18:44 +0900
parents 91f5c9dc91c8
children 96e15614a31f
line wrap: on
line source

// Copyright (C) 2010, 2011, 2012, 2013 GlavSoft LLC.
// All rights reserved.
//
//-------------------------------------------------------------------------
// This file is part of the TightVNC software.  Please visit our Web site:
//
//                       http://www.tightvnc.com/
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License along
// with this program; if not, write to the Free Software Foundation, Inc.,
// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
//-------------------------------------------------------------------------
//

package com.glavsoft.rfb.encoding.decoder;

import com.glavsoft.drawing.Renderer;
import com.glavsoft.exceptions.TransportException;
import com.glavsoft.rfb.encoding.EncodingType;
import com.glavsoft.transport.Reader;
import jp.ac.u_ryukyu.treevnc.CheckDelay;
import jp.ac.u_ryukyu.treevnc.TreeRFBProto;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.util.zip.DataFormatException;
import java.util.zip.Deflater;

public class ZRLEDecoder extends ZlibDecoder {
	private static final int MAX_TILE_SIZE = 64;
    private int[] decodedBitmap;
    private int[] palette;

	private int deflate_size = 65507;
	private ByteBuffer c1;
	private FramebufferUpdateRectangle c1rect;
	private int c1headerPos;

	@Override
	public void decode(Reader reader, Renderer renderer,
                       FramebufferUpdateRectangle rect) throws TransportException {
		int zippedLength = (int) reader.readUInt32();
		if (0 == zippedLength) return;
		int length = rect.width * rect.height * renderer.getBytesPerPixel();
		byte[] bytes = unzip(reader, zippedLength, length, rect.getEncodingType());
		decode1(renderer, null, rect, bytes, zippedLength, null);
    }
    
	public void decode1(Renderer renderer, ByteBuffer header, FramebufferUpdateRectangle rect, byte[] bytes, int zippedLength, TreeRFBProto rfbProto) throws TransportException {
		int offset = zippedLength;
		int maxX = rect.x + rect.width;
		int maxY = rect.y + rect.height;
		int prevoffset = offset;
		//System.out.println("decode1: "+rect);
        if (null == palette) {
            palette = new int [128];
        }
        if (null == decodedBitmap) {
            decodedBitmap = new int[MAX_TILE_SIZE * MAX_TILE_SIZE];
        }

		if (rfbProto.multicastBlocking)  {
			try {
				zrleeBlocking(rfbProto, header, bytes, rect);
			} catch (DataFormatException e) {
				e.printStackTrace();
			}
		}
		for (int tileY = rect.y; tileY < maxY; tileY += MAX_TILE_SIZE) {
			int tileHeight = Math.min(maxY - tileY, MAX_TILE_SIZE);

			for (int tileX = rect.x; tileX < maxX; tileX += MAX_TILE_SIZE) {
				int tileWidth = Math.min(maxX - tileX, MAX_TILE_SIZE);
				int subencoding = bytes[offset++] & 0x0ff;
				if(subencoding!=0)
					System.out.println("----------------"+subencoding);
				// 128 -plain RLE, 130-255 - Palette RLE
				boolean isRle = (subencoding & 128) != 0;
				// 2 to 16 for raw packed palette data, 130 to 255 for Palette RLE (subencoding - 128)
				int paletteSize = subencoding & 127;
				offset += readPalette(bytes, offset, renderer, paletteSize);
				if (1 == subencoding) { // A solid tile consisting of a single colour
					renderer.fillRect(palette[0], tileX, tileY, tileWidth, tileHeight);
				} else if (isRle) {
					if (0 == paletteSize) { // subencoding == 128 (or paletteSize == 0) - Plain RLE
						offset += decodePlainRle(bytes, offset, renderer, tileX, tileY, tileWidth, tileHeight);
					} else {
						offset += decodePaletteRle(bytes, offset, renderer, tileX, tileY, tileWidth, tileHeight);
					}
				} else {
					if (0 == paletteSize) { // subencoding == 0 (or paletteSize == 0) - raw CPIXEL data
						offset += decodeRaw(bytes, offset, renderer, tileX, tileY, tileWidth, tileHeight);
//						System.out.println("offset:"+offset);
					} else {
						offset += decodePacked(bytes, offset, renderer, paletteSize, tileX, tileY, tileWidth, tileHeight);
					}
				}
				if (rfbProto != null && rfbProto.multicastBlocking) multicastPut(rfbProto, rect, bytes, prevoffset, offset, tileX, tileY,tileWidth, tileHeight);
				prevoffset = offset;
			}
		}
	}

	private int decodePlainRle(byte[] bytes, int offset, Renderer renderer,
			int tileX, int tileY, int tileWidth, int tileHeight) {
		int bytesPerCPixel = renderer.getBytesPerCPixel();
		int decodedOffset = 0;
		int decodedEnd = tileWidth * tileHeight;
		int index = offset;
		while (decodedOffset < decodedEnd) {
			int color = renderer.getCompactPixelColor(bytes, index);
			index += bytesPerCPixel;
			int rlength = 1;
			do {
				rlength += bytes[index] & 0x0ff;
			} while ((bytes[index++] & 0x0ff) == 255);
			assert rlength <= decodedEnd - decodedOffset;
			renderer.fillColorBitmapWithColor(decodedBitmap, decodedOffset, rlength, color);
			decodedOffset += rlength;
		}
		renderer.drawColoredBitmap(decodedBitmap, tileX, tileY, tileWidth, tileHeight);
		return index - offset;
	}

	private int decodePaletteRle(byte[] bytes, int offset, Renderer renderer,
                                 int tileX, int tileY, int tileWidth, int tileHeight) {
		int decodedOffset = 0;
		int decodedEnd = tileWidth * tileHeight;
		int index = offset;
		while (decodedOffset < decodedEnd) {
			int colorIndex = bytes[index++];
			int color = palette[colorIndex & 127];
			int rlength = 1;
			if ((colorIndex & 128) != 0) {
				do {
					rlength += bytes[index] & 0x0ff;
				} while (bytes[index++] == (byte) 255);
			}
			assert rlength <= decodedEnd - decodedOffset;
			renderer.fillColorBitmapWithColor(decodedBitmap, decodedOffset, rlength, color);
			decodedOffset += rlength;
		}
		renderer.drawColoredBitmap(decodedBitmap, tileX, tileY, tileWidth, tileHeight);
		return index - offset;
	}

	private int decodePacked(byte[] bytes, int offset, Renderer renderer,
                             int paletteSize, int tileX, int tileY, int tileWidth, int tileHeight) {
		int bitsPerPalletedPixel = paletteSize > 16 ? 8 : paletteSize > 4 ? 4
				: paletteSize > 2 ? 2 : 1;
		int packedOffset = offset;
		int decodedOffset = 0;
		for (int i = 0; i < tileHeight; ++i) {
			int decodedRowEnd = decodedOffset + tileWidth;
			int byteProcessed = 0;
			int bitsRemain = 0;

			while (decodedOffset < decodedRowEnd) {
				if (bitsRemain == 0) {
					byteProcessed = bytes[packedOffset++];
					bitsRemain = 8;
				}
				bitsRemain -= bitsPerPalletedPixel;
				int index = byteProcessed >> bitsRemain & (1 << bitsPerPalletedPixel) - 1 & 127;
				int color = palette[index];
				renderer.fillColorBitmapWithColor(decodedBitmap, decodedOffset, 1, color);
				++decodedOffset;
			}
		}
		renderer.drawColoredBitmap(decodedBitmap, tileX, tileY, tileWidth, tileHeight);
		return packedOffset - offset;
	}

	private int decodeRaw(byte[] bytes, int offset, Renderer renderer,
			int tileX, int tileY, int tileWidth, int tileHeight) throws TransportException {
		return renderer.drawCompactBytes(bytes, offset, tileX, tileY, tileWidth, tileHeight);
	}

	private int readPalette(byte[] bytes, int offset, Renderer renderer, int paletteSize) {
        final int bytesPerCPixel = renderer.getBytesPerCPixel();
		for (int i=0; i<paletteSize; ++i) {
            palette[i] = renderer.getCompactPixelColor(bytes, offset + i* bytesPerCPixel);
		}
		return paletteSize * bytesPerCPixel;
	}


	/**
	 * Multicast framebufferUpdate to children.
	 * read FrameBuffferUpdate. If it is ZLE, make it ZLEE which is self contained compressed packet.
	 * put the packet to the multicastqueue. Then normal rendering engine read the same stream using is.reset().
	 *
	 * @throws TransportException
	 * @throws UnsupportedEncodingException
	 */


	private void zrleeBlocking(TreeRFBProto rfb, ByteBuffer header, byte[] bytes, FramebufferUpdateRectangle rect) throws TransportException, DataFormatException {
		// dump32(inputs);
		c1 = rfb.multicastqueue.allocate(deflate_size);
		if (rfb.addSerialNum)
			c1.putLong(rfb.counter++);
		if (rfb.checkDelay)
			CheckDelay.checkDelay(c1, rect.x, rect.y, rect.width, rect.height, System.currentTimeMillis(), EncodingType.CHECK_DELAY);
		c1headerPos = c1.position();
		c1.put(header);
		header.flip();
		c1.putInt(0);
		c1rect = new FramebufferUpdateRectangle(rect.x, rect.y, 0, 0);
		return;
	}

	public void multicastPut(TreeRFBProto rfb, ByteBuffer header, FramebufferUpdateRectangle rect, byte[] bytes, int prevoffset, int offset, int tileX, int tileY, int tileW, int tileH) {
		int span = offset - prevoffset;
		rfb.deflater.setInput(bytes,prevoffset,span);
		c1rect.height = tileH;
		if (c1.remaining() < span || c1rect.x + c1rect.width + tileW >= rect.x + rect.width ) {
			rfb.deflater.deflate(c1, Deflater.FULL_FLUSH);
			rfb.deflater.finish();
			c1.flip();
			//System.out.println("multicastPut: " + c1rect + " length: " + (c1.remaining()-c1headerPos-header.limit()));
			try {
				rfb.writeUpdateRectangleWithHeader(c1, c1headerPos, c1.remaining()-c1headerPos-header.limit()-4, c1rect.x, c1rect.y, c1rect.width + tileW, c1rect.height + tileY);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			c1rect.x += c1rect.width;
			if (c1rect.x >= rect.x + rect.width) {
				c1rect.x = rect.x;
				c1rect.y += tileH;
			}
			c1rect.width = 0;
			c1 = rfb.multicastqueue.allocate(deflate_size);
			if (rfb.addSerialNum)
				c1.putLong(rfb.counter++);
			c1headerPos = c1.position();
			c1.put(header);
			header.flip();
			c1.putInt(0);
		} else {
			rfb.deflater.deflate(c1, Deflater.SYNC_FLUSH);
		}
		c1rect.width += tileW;
	}
}