summaryrefslogtreecommitdiffstats
path: root/java/src/com/tigervnc/decoder/ZlibDecoder.java
blob: 1370da1579b263ef582bb416d80b93f535e4e613 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
package com.tightvnc.decoder;

import com.tightvnc.vncviewer.RfbInputStream;
import java.awt.Graphics;
import java.io.IOException;
import java.util.zip.DataFormatException;
import java.util.zip.Inflater;

//
// Class that used for decoding ZLib encoded data.
//

public class ZlibDecoder extends RawDecoder {

  final static int EncodingZlib = 6;

  public ZlibDecoder(Graphics g, RfbInputStream is) {
    super(g, is);
  }

  public ZlibDecoder(Graphics g, RfbInputStream is, int frameBufferW,
                     int frameBufferH) {
    super(g, is, frameBufferW, frameBufferH);
  }

  //
  // Override handleRect method to decode ZLib encoded data insted of
  // raw pixel data.
  //

  public void handleRect(int x, int y, int w, int h) throws IOException  {

    //
    // Write encoding ID to record output stream.
    // Remark: we forced changed encoding from zlib to raw
    // cause at this moment we cannot save data in zlib encoding.
    //

    if (dos != null) {
      dos.writeInt(RawDecoder.EncodingRaw);
    }

    int nBytes = rfbis.readU32();

    if (zlibBuf == null || zlibBufLen < nBytes) {
      zlibBufLen = nBytes * 2;
      zlibBuf = new byte[zlibBufLen];
    }

    rfbis.readFully(zlibBuf, 0, nBytes);

    if (zlibInflater == null) {
      zlibInflater = new Inflater();
    }
    zlibInflater.setInput(zlibBuf, 0, nBytes);

    try {
      if (bytesPerPixel == 1) {
        for (int dy = y; dy < y + h; dy++) {
          zlibInflater.inflate(pixels8, dy * framebufferWidth + x, w);

          //
          // Save decoded raw data to data output stream
          //

          if (dos != null)
            dos.write(pixels8, dy * framebufferWidth + x, w);
        }
      } else {
        byte[] buf = new byte[w * 4];
        int i, offset;
        for (int dy = y; dy < y + h; dy++) {
          zlibInflater.inflate(buf);
          offset = dy * framebufferWidth + x;
          for (i = 0; i < w; i++) {
            RawDecoder.pixels24[offset + i] =
              (buf[i * 4 + 2] & 0xFF) << 16 |
              (buf[i * 4 + 1] & 0xFF) << 8 |
              (buf[i * 4] & 0xFF);
          }

          //
          // Save decoded raw data to data output stream
          //

          if (dos != null)
            dos.write(buf);
        }
      }
    } catch (DataFormatException ex) {
      ex.printStackTrace();
    }
    handleUpdatedPixels(x, y, w, h);
  }

  //
  // Zlib encoder's data.
  //

  protected byte[] zlibBuf;
  protected int zlibBufLen = 0;
  protected Inflater zlibInflater;
}