blob: fcdbbfa1a65135dd237dd68dac94642ddf923a1f [file] [log] [blame]
Constantin Kaplinsky2844fd52008-04-14 08:02:25 +00001//
2// Copyright (C) 2001-2004 HorizonLive.com, Inc. All Rights Reserved.
3// Copyright (C) 2001-2006 Constantin Kaplinsky. All Rights Reserved.
4// Copyright (C) 2000 Tridia Corporation. All Rights Reserved.
5// Copyright (C) 1999 AT&T Laboratories Cambridge. All Rights Reserved.
6//
7// This is free software; you can redistribute it and/or modify
8// it under the terms of the GNU General Public License as published by
9// the Free Software Foundation; either version 2 of the License, or
10// (at your option) any later version.
11//
12// This software is distributed in the hope that it will be useful,
13// but WITHOUT ANY WARRANTY; without even the implied warranty of
14// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15// GNU General Public License for more details.
16//
17// You should have received a copy of the GNU General Public License
18// along with this software; if not, write to the Free Software
19// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
20// USA.
21//
22
23//
24// RfbProto.java
25//
26
Constantin Kaplinsky90d8a502008-04-14 09:45:50 +000027package com.tightvnc.vncviewer;
28
Constantin Kaplinsky2844fd52008-04-14 08:02:25 +000029import java.io.*;
30import java.awt.*;
31import java.awt.event.*;
32import java.net.Socket;
33import java.util.zip.*;
34
35class RfbProto {
36
37 final static String
38 versionMsg_3_3 = "RFB 003.003\n",
39 versionMsg_3_7 = "RFB 003.007\n",
40 versionMsg_3_8 = "RFB 003.008\n";
41
42 // Vendor signatures: standard VNC/RealVNC, TridiaVNC, and TightVNC
43 final static String
44 StandardVendor = "STDV",
45 TridiaVncVendor = "TRDV",
46 TightVncVendor = "TGHT";
47
48 // Security types
49 final static int
50 SecTypeInvalid = 0,
51 SecTypeNone = 1,
52 SecTypeVncAuth = 2,
53 SecTypeTight = 16;
54
55 // Supported tunneling types
56 final static int
57 NoTunneling = 0;
58 final static String
59 SigNoTunneling = "NOTUNNEL";
60
61 // Supported authentication types
62 final static int
63 AuthNone = 1,
64 AuthVNC = 2,
65 AuthUnixLogin = 129;
66 final static String
67 SigAuthNone = "NOAUTH__",
68 SigAuthVNC = "VNCAUTH_",
69 SigAuthUnixLogin = "ULGNAUTH";
70
71 // VNC authentication results
72 final static int
73 VncAuthOK = 0,
74 VncAuthFailed = 1,
75 VncAuthTooMany = 2;
76
77 // Standard server-to-client messages
78 final static int
79 FramebufferUpdate = 0,
80 SetColourMapEntries = 1,
81 Bell = 2,
82 ServerCutText = 3;
83
84 // Non-standard server-to-client messages
85 final static int
86 EndOfContinuousUpdates = 150;
87 final static String
88 SigEndOfContinuousUpdates = "CUS_EOCU";
89
90 // Standard client-to-server messages
91 final static int
92 SetPixelFormat = 0,
93 FixColourMapEntries = 1,
94 SetEncodings = 2,
95 FramebufferUpdateRequest = 3,
96 KeyboardEvent = 4,
97 PointerEvent = 5,
98 ClientCutText = 6;
99
100 // Non-standard client-to-server messages
Constantin Kaplinskyf7cb2bf2008-05-27 08:38:28 +0000101 final static int EnableContinuousUpdates = 150;
102 final static int VideoRectangleSelection = 151;
103 final static String SigEnableContinuousUpdates = "CUC_ENCU";
104 final static String SigVideoRectangleSelection = "VRECTSEL";
Constantin Kaplinsky2844fd52008-04-14 08:02:25 +0000105
106 // Supported encodings and pseudo-encodings
107 final static int
108 EncodingRaw = 0,
109 EncodingCopyRect = 1,
110 EncodingRRE = 2,
111 EncodingCoRRE = 4,
112 EncodingHextile = 5,
113 EncodingZlib = 6,
114 EncodingTight = 7,
115 EncodingZRLE = 16,
116 EncodingCompressLevel0 = 0xFFFFFF00,
117 EncodingQualityLevel0 = 0xFFFFFFE0,
118 EncodingXCursor = 0xFFFFFF10,
119 EncodingRichCursor = 0xFFFFFF11,
120 EncodingPointerPos = 0xFFFFFF18,
121 EncodingLastRect = 0xFFFFFF20,
122 EncodingNewFBSize = 0xFFFFFF21;
123 final static String
124 SigEncodingRaw = "RAW_____",
125 SigEncodingCopyRect = "COPYRECT",
126 SigEncodingRRE = "RRE_____",
127 SigEncodingCoRRE = "CORRE___",
128 SigEncodingHextile = "HEXTILE_",
129 SigEncodingZlib = "ZLIB____",
130 SigEncodingTight = "TIGHT___",
131 SigEncodingZRLE = "ZRLE____",
132 SigEncodingCompressLevel0 = "COMPRLVL",
133 SigEncodingQualityLevel0 = "JPEGQLVL",
134 SigEncodingXCursor = "X11CURSR",
135 SigEncodingRichCursor = "RCHCURSR",
136 SigEncodingPointerPos = "POINTPOS",
137 SigEncodingLastRect = "LASTRECT",
138 SigEncodingNewFBSize = "NEWFBSIZ";
139
140 final static int MaxNormalEncoding = 255;
141
142 // Contstants used in the Hextile decoder
143 final static int
144 HextileRaw = 1,
145 HextileBackgroundSpecified = 2,
146 HextileForegroundSpecified = 4,
147 HextileAnySubrects = 8,
148 HextileSubrectsColoured = 16;
149
150 // Contstants used in the Tight decoder
151 final static int TightMinToCompress = 12;
152 final static int
153 TightExplicitFilter = 0x04,
154 TightFill = 0x08,
155 TightJpeg = 0x09,
156 TightMaxSubencoding = 0x09,
157 TightFilterCopy = 0x00,
158 TightFilterPalette = 0x01,
159 TightFilterGradient = 0x02;
160
161
162 String host;
163 int port;
164 Socket sock;
165 OutputStream os;
166 SessionRecorder rec;
167 boolean inNormalProtocol = false;
168 VncViewer viewer;
169
170 // Input stream is declared private to make sure it can be accessed
171 // only via RfbProto methods. We have to do this because we want to
172 // count how many bytes were read.
173 private DataInputStream is;
174 private long numBytesRead = 0;
175 public long getNumBytesRead() { return numBytesRead; }
176
177 // Java on UNIX does not call keyPressed() on some keys, for example
178 // swedish keys To prevent our workaround to produce duplicate
179 // keypresses on JVMs that actually works, keep track of if
180 // keyPressed() for a "broken" key was called or not.
181 boolean brokenKeyPressed = false;
182
183 // This will be set to true on the first framebuffer update
184 // containing Zlib-, ZRLE- or Tight-encoded data.
185 boolean wereZlibUpdates = false;
186
187 // This will be set to false if the startSession() was called after
188 // we have received at least one Zlib-, ZRLE- or Tight-encoded
189 // framebuffer update.
190 boolean recordFromBeginning = true;
191
192 // This fields are needed to show warnings about inefficiently saved
193 // sessions only once per each saved session file.
194 boolean zlibWarningShown;
195 boolean tightWarningShown;
196
197 // Before starting to record each saved session, we set this field
198 // to 0, and increment on each framebuffer update. We don't flush
199 // the SessionRecorder data into the file before the second update.
200 // This allows us to write initial framebuffer update with zero
201 // timestamp, to let the player show initial desktop before
202 // playback.
203 int numUpdatesInSession;
204
205 // Measuring network throughput.
206 boolean timing;
207 long timeWaitedIn100us;
208 long timedKbits;
209
210 // Protocol version and TightVNC-specific protocol options.
211 int serverMajor, serverMinor;
212 int clientMajor, clientMinor;
213 boolean protocolTightVNC;
214 CapsContainer tunnelCaps, authCaps;
215 CapsContainer serverMsgCaps, clientMsgCaps;
216 CapsContainer encodingCaps;
217
218 // "Continuous updates" is a TightVNC-specific feature that allows
219 // receiving framebuffer updates continuously, without sending update
220 // requests. The variables below track the state of this feature.
221 // Initially, continuous updates are disabled. They can be enabled
222 // by calling tryEnableContinuousUpdates() method, and only if this
223 // feature is supported by the server. To disable continuous updates,
224 // tryDisableContinuousUpdates() should be called.
225 private boolean continuousUpdatesActive = false;
226 private boolean continuousUpdatesEnding = false;
227
228 // If true, informs that the RFB socket was closed.
229 private boolean closed;
230
231 //
232 // Constructor. Make TCP connection to RFB server.
233 //
234
235 RfbProto(String h, int p, VncViewer v) throws IOException {
236 viewer = v;
237 host = h;
238 port = p;
239
240 if (viewer.socketFactory == null) {
241 sock = new Socket(host, port);
enikey17ac1812008-12-19 11:22:13 +0000242 sock.setTcpNoDelay(true);
Constantin Kaplinsky2844fd52008-04-14 08:02:25 +0000243 } else {
244 try {
245 Class factoryClass = Class.forName(viewer.socketFactory);
246 SocketFactory factory = (SocketFactory)factoryClass.newInstance();
247 if (viewer.inAnApplet)
248 sock = factory.createSocket(host, port, viewer);
249 else
250 sock = factory.createSocket(host, port, viewer.mainArgs);
251 } catch(Exception e) {
252 e.printStackTrace();
253 throw new IOException(e.getMessage());
254 }
255 }
256 is = new DataInputStream(new BufferedInputStream(sock.getInputStream(),
257 16384));
258 os = sock.getOutputStream();
259
260 timing = false;
261 timeWaitedIn100us = 5;
262 timedKbits = 0;
263 }
264
265
266 synchronized void close() {
267 try {
268 sock.close();
269 closed = true;
270 System.out.println("RFB socket closed");
271 if (rec != null) {
272 rec.close();
273 rec = null;
274 }
275 } catch (Exception e) {
276 e.printStackTrace();
277 }
278 }
279
280 synchronized boolean closed() {
281 return closed;
282 }
283
284 //
285 // Read server's protocol version message
286 //
287
288 void readVersionMsg() throws Exception {
289
290 byte[] b = new byte[12];
291
292 readFully(b);
293
294 if ((b[0] != 'R') || (b[1] != 'F') || (b[2] != 'B') || (b[3] != ' ')
295 || (b[4] < '0') || (b[4] > '9') || (b[5] < '0') || (b[5] > '9')
296 || (b[6] < '0') || (b[6] > '9') || (b[7] != '.')
297 || (b[8] < '0') || (b[8] > '9') || (b[9] < '0') || (b[9] > '9')
298 || (b[10] < '0') || (b[10] > '9') || (b[11] != '\n'))
299 {
300 throw new Exception("Host " + host + " port " + port +
301 " is not an RFB server");
302 }
303
304 serverMajor = (b[4] - '0') * 100 + (b[5] - '0') * 10 + (b[6] - '0');
305 serverMinor = (b[8] - '0') * 100 + (b[9] - '0') * 10 + (b[10] - '0');
306
307 if (serverMajor < 3) {
308 throw new Exception("RFB server does not support protocol version 3");
309 }
310 }
311
312
313 //
314 // Write our protocol version message
315 //
316
317 void writeVersionMsg() throws IOException {
318 clientMajor = 3;
319 if (serverMajor > 3 || serverMinor >= 8) {
320 clientMinor = 8;
321 os.write(versionMsg_3_8.getBytes());
322 } else if (serverMinor >= 7) {
323 clientMinor = 7;
324 os.write(versionMsg_3_7.getBytes());
325 } else {
326 clientMinor = 3;
327 os.write(versionMsg_3_3.getBytes());
328 }
329 protocolTightVNC = false;
330 initCapabilities();
331 }
332
333
334 //
335 // Negotiate the authentication scheme.
336 //
337
338 int negotiateSecurity() throws Exception {
339 return (clientMinor >= 7) ?
340 selectSecurityType() : readSecurityType();
341 }
342
343 //
344 // Read security type from the server (protocol version 3.3).
345 //
346
347 int readSecurityType() throws Exception {
348 int secType = readU32();
349
350 switch (secType) {
351 case SecTypeInvalid:
352 readConnFailedReason();
353 return SecTypeInvalid; // should never be executed
354 case SecTypeNone:
355 case SecTypeVncAuth:
356 return secType;
357 default:
358 throw new Exception("Unknown security type from RFB server: " + secType);
359 }
360 }
361
362 //
363 // Select security type from the server's list (protocol versions 3.7/3.8).
364 //
365
366 int selectSecurityType() throws Exception {
367 int secType = SecTypeInvalid;
368
369 // Read the list of secutiry types.
370 int nSecTypes = readU8();
371 if (nSecTypes == 0) {
372 readConnFailedReason();
373 return SecTypeInvalid; // should never be executed
374 }
375 byte[] secTypes = new byte[nSecTypes];
376 readFully(secTypes);
377
378 // Find out if the server supports TightVNC protocol extensions
379 for (int i = 0; i < nSecTypes; i++) {
380 if (secTypes[i] == SecTypeTight) {
381 protocolTightVNC = true;
382 os.write(SecTypeTight);
383 return SecTypeTight;
384 }
385 }
386
387 // Find first supported security type.
388 for (int i = 0; i < nSecTypes; i++) {
389 if (secTypes[i] == SecTypeNone || secTypes[i] == SecTypeVncAuth) {
390 secType = secTypes[i];
391 break;
392 }
393 }
394
395 if (secType == SecTypeInvalid) {
396 throw new Exception("Server did not offer supported security type");
397 } else {
398 os.write(secType);
399 }
400
401 return secType;
402 }
403
404 //
405 // Perform "no authentication".
406 //
407
408 void authenticateNone() throws Exception {
409 if (clientMinor >= 8)
410 readSecurityResult("No authentication");
411 }
412
413 //
414 // Perform standard VNC Authentication.
415 //
416
417 void authenticateVNC(String pw) throws Exception {
418 byte[] challenge = new byte[16];
419 readFully(challenge);
420
421 if (pw.length() > 8)
422 pw = pw.substring(0, 8); // Truncate to 8 chars
423
424 // Truncate password on the first zero byte.
425 int firstZero = pw.indexOf(0);
426 if (firstZero != -1)
427 pw = pw.substring(0, firstZero);
428
429 byte[] key = {0, 0, 0, 0, 0, 0, 0, 0};
430 System.arraycopy(pw.getBytes(), 0, key, 0, pw.length());
431
432 DesCipher des = new DesCipher(key);
433
434 des.encrypt(challenge, 0, challenge, 0);
435 des.encrypt(challenge, 8, challenge, 8);
436
437 os.write(challenge);
438
439 readSecurityResult("VNC authentication");
440 }
441
442 //
443 // Read security result.
444 // Throws an exception on authentication failure.
445 //
446
447 void readSecurityResult(String authType) throws Exception {
448 int securityResult = readU32();
449
450 switch (securityResult) {
451 case VncAuthOK:
452 System.out.println(authType + ": success");
453 break;
454 case VncAuthFailed:
455 if (clientMinor >= 8)
456 readConnFailedReason();
457 throw new Exception(authType + ": failed");
458 case VncAuthTooMany:
459 throw new Exception(authType + ": failed, too many tries");
460 default:
461 throw new Exception(authType + ": unknown result " + securityResult);
462 }
463 }
464
465 //
466 // Read the string describing the reason for a connection failure,
467 // and throw an exception.
468 //
469
470 void readConnFailedReason() throws Exception {
471 int reasonLen = readU32();
472 byte[] reason = new byte[reasonLen];
473 readFully(reason);
474 throw new Exception(new String(reason));
475 }
476
477 //
478 // Initialize capability lists (TightVNC protocol extensions).
479 //
480
481 void initCapabilities() {
482 tunnelCaps = new CapsContainer();
483 authCaps = new CapsContainer();
484 serverMsgCaps = new CapsContainer();
485 clientMsgCaps = new CapsContainer();
486 encodingCaps = new CapsContainer();
487
488 // Supported authentication methods
489 authCaps.add(AuthNone, StandardVendor, SigAuthNone,
490 "No authentication");
491 authCaps.add(AuthVNC, StandardVendor, SigAuthVNC,
492 "Standard VNC password authentication");
493
494 // Supported non-standard server-to-client messages
495 serverMsgCaps.add(EndOfContinuousUpdates, TightVncVendor,
496 SigEndOfContinuousUpdates,
497 "End of continuous updates notification");
498
499 // Supported non-standard client-to-server messages
500 clientMsgCaps.add(EnableContinuousUpdates, TightVncVendor,
501 SigEnableContinuousUpdates,
502 "Enable/disable continuous updates");
Constantin Kaplinskyf7cb2bf2008-05-27 08:38:28 +0000503 clientMsgCaps.add(VideoRectangleSelection, TightVncVendor,
504 SigVideoRectangleSelection,
505 "Select a rectangle to be treated as video");
Constantin Kaplinsky2844fd52008-04-14 08:02:25 +0000506
507 // Supported encoding types
508 encodingCaps.add(EncodingCopyRect, StandardVendor,
509 SigEncodingCopyRect, "Standard CopyRect encoding");
510 encodingCaps.add(EncodingRRE, StandardVendor,
511 SigEncodingRRE, "Standard RRE encoding");
512 encodingCaps.add(EncodingCoRRE, StandardVendor,
513 SigEncodingCoRRE, "Standard CoRRE encoding");
514 encodingCaps.add(EncodingHextile, StandardVendor,
515 SigEncodingHextile, "Standard Hextile encoding");
516 encodingCaps.add(EncodingZRLE, StandardVendor,
517 SigEncodingZRLE, "Standard ZRLE encoding");
518 encodingCaps.add(EncodingZlib, TridiaVncVendor,
519 SigEncodingZlib, "Zlib encoding");
520 encodingCaps.add(EncodingTight, TightVncVendor,
521 SigEncodingTight, "Tight encoding");
522
523 // Supported pseudo-encoding types
524 encodingCaps.add(EncodingCompressLevel0, TightVncVendor,
525 SigEncodingCompressLevel0, "Compression level");
526 encodingCaps.add(EncodingQualityLevel0, TightVncVendor,
527 SigEncodingQualityLevel0, "JPEG quality level");
528 encodingCaps.add(EncodingXCursor, TightVncVendor,
529 SigEncodingXCursor, "X-style cursor shape update");
530 encodingCaps.add(EncodingRichCursor, TightVncVendor,
531 SigEncodingRichCursor, "Rich-color cursor shape update");
532 encodingCaps.add(EncodingPointerPos, TightVncVendor,
533 SigEncodingPointerPos, "Pointer position update");
534 encodingCaps.add(EncodingLastRect, TightVncVendor,
535 SigEncodingLastRect, "LastRect protocol extension");
536 encodingCaps.add(EncodingNewFBSize, TightVncVendor,
537 SigEncodingNewFBSize, "Framebuffer size change");
538 }
539
540 //
541 // Setup tunneling (TightVNC protocol extensions)
542 //
543
544 void setupTunneling() throws IOException {
545 int nTunnelTypes = readU32();
546 if (nTunnelTypes != 0) {
547 readCapabilityList(tunnelCaps, nTunnelTypes);
548
549 // We don't support tunneling yet.
550 writeInt(NoTunneling);
551 }
552 }
553
554 //
555 // Negotiate authentication scheme (TightVNC protocol extensions)
556 //
557
558 int negotiateAuthenticationTight() throws Exception {
559 int nAuthTypes = readU32();
560 if (nAuthTypes == 0)
561 return AuthNone;
562
563 readCapabilityList(authCaps, nAuthTypes);
564 for (int i = 0; i < authCaps.numEnabled(); i++) {
565 int authType = authCaps.getByOrder(i);
566 if (authType == AuthNone || authType == AuthVNC) {
567 writeInt(authType);
568 return authType;
569 }
570 }
571 throw new Exception("No suitable authentication scheme found");
572 }
573
574 //
575 // Read a capability list (TightVNC protocol extensions)
576 //
577
578 void readCapabilityList(CapsContainer caps, int count) throws IOException {
579 int code;
580 byte[] vendor = new byte[4];
581 byte[] name = new byte[8];
582 for (int i = 0; i < count; i++) {
583 code = readU32();
584 readFully(vendor);
585 readFully(name);
586 caps.enable(new CapabilityInfo(code, vendor, name));
587 }
588 }
589
590 //
591 // Write a 32-bit integer into the output stream.
592 //
593
594 void writeInt(int value) throws IOException {
595 byte[] b = new byte[4];
596 b[0] = (byte) ((value >> 24) & 0xff);
597 b[1] = (byte) ((value >> 16) & 0xff);
598 b[2] = (byte) ((value >> 8) & 0xff);
599 b[3] = (byte) (value & 0xff);
600 os.write(b);
601 }
602
603 //
604 // Write the client initialisation message
605 //
606
607 void writeClientInit() throws IOException {
608 if (viewer.options.shareDesktop) {
609 os.write(1);
610 } else {
611 os.write(0);
612 }
613 viewer.options.disableShareDesktop();
614 }
615
616
617 //
618 // Read the server initialisation message
619 //
620
621 String desktopName;
622 int framebufferWidth, framebufferHeight;
623 int bitsPerPixel, depth;
624 boolean bigEndian, trueColour;
625 int redMax, greenMax, blueMax, redShift, greenShift, blueShift;
626
627 void readServerInit() throws IOException {
628 framebufferWidth = readU16();
629 framebufferHeight = readU16();
630 bitsPerPixel = readU8();
631 depth = readU8();
632 bigEndian = (readU8() != 0);
633 trueColour = (readU8() != 0);
634 redMax = readU16();
635 greenMax = readU16();
636 blueMax = readU16();
637 redShift = readU8();
638 greenShift = readU8();
639 blueShift = readU8();
640 byte[] pad = new byte[3];
641 readFully(pad);
642 int nameLength = readU32();
643 byte[] name = new byte[nameLength];
644 readFully(name);
645 desktopName = new String(name);
646
647 // Read interaction capabilities (TightVNC protocol extensions)
648 if (protocolTightVNC) {
649 int nServerMessageTypes = readU16();
650 int nClientMessageTypes = readU16();
651 int nEncodingTypes = readU16();
652 readU16();
653 readCapabilityList(serverMsgCaps, nServerMessageTypes);
654 readCapabilityList(clientMsgCaps, nClientMessageTypes);
655 readCapabilityList(encodingCaps, nEncodingTypes);
656 }
657
658 if (!clientMsgCaps.isEnabled(EnableContinuousUpdates)) {
659 viewer.options.disableContUpdates();
660 }
661
662 inNormalProtocol = true;
663 }
664
665
666 //
667 // Create session file and write initial protocol messages into it.
668 //
669
670 void startSession(String fname) throws IOException {
671 rec = new SessionRecorder(fname);
672 rec.writeHeader();
673 rec.write(versionMsg_3_3.getBytes());
674 rec.writeIntBE(SecTypeNone);
675 rec.writeShortBE(framebufferWidth);
676 rec.writeShortBE(framebufferHeight);
677 byte[] fbsServerInitMsg = {
678 32, 24, 0, 1, 0,
679 (byte)0xFF, 0, (byte)0xFF, 0, (byte)0xFF,
680 16, 8, 0, 0, 0, 0
681 };
682 rec.write(fbsServerInitMsg);
683 rec.writeIntBE(desktopName.length());
684 rec.write(desktopName.getBytes());
685 numUpdatesInSession = 0;
686
687 // FIXME: If there were e.g. ZRLE updates only, that should not
688 // affect recording of Zlib and Tight updates. So, actually
689 // we should maintain separate flags for Zlib, ZRLE and
690 // Tight, instead of one ``wereZlibUpdates'' variable.
691 //
692 if (wereZlibUpdates)
693 recordFromBeginning = false;
694
695 zlibWarningShown = false;
696 tightWarningShown = false;
697 }
698
699 //
700 // Close session file.
701 //
702
703 void closeSession() throws IOException {
704 if (rec != null) {
705 rec.close();
706 rec = null;
707 }
708 }
709
710
711 //
712 // Set new framebuffer size
713 //
714
715 void setFramebufferSize(int width, int height) {
716 framebufferWidth = width;
717 framebufferHeight = height;
718 }
719
720
721 //
722 // Read the server message type
723 //
724
725 int readServerMessageType() throws IOException {
726 int msgType = readU8();
727
728 // If the session is being recorded:
729 if (rec != null) {
730 if (msgType == Bell) { // Save Bell messages in session files.
731 rec.writeByte(msgType);
732 if (numUpdatesInSession > 0)
733 rec.flush();
734 }
735 }
736
737 return msgType;
738 }
739
740
741 //
742 // Read a FramebufferUpdate message
743 //
744
745 int updateNRects;
746
747 void readFramebufferUpdate() throws IOException {
748 skipBytes(1);
749 updateNRects = readU16();
750
751 // If the session is being recorded:
752 if (rec != null) {
753 rec.writeByte(FramebufferUpdate);
754 rec.writeByte(0);
755 rec.writeShortBE(updateNRects);
756 }
757
758 numUpdatesInSession++;
759 }
760
761 // Read a FramebufferUpdate rectangle header
762
763 int updateRectX, updateRectY, updateRectW, updateRectH, updateRectEncoding;
764
765 void readFramebufferUpdateRectHdr() throws Exception {
766 updateRectX = readU16();
767 updateRectY = readU16();
768 updateRectW = readU16();
769 updateRectH = readU16();
770 updateRectEncoding = readU32();
771
772 if (updateRectEncoding == EncodingZlib ||
773 updateRectEncoding == EncodingZRLE ||
774 updateRectEncoding == EncodingTight)
775 wereZlibUpdates = true;
776
777 // If the session is being recorded:
778 if (rec != null) {
779 if (numUpdatesInSession > 1)
780 rec.flush(); // Flush the output on each rectangle.
781 rec.writeShortBE(updateRectX);
782 rec.writeShortBE(updateRectY);
783 rec.writeShortBE(updateRectW);
784 rec.writeShortBE(updateRectH);
785 if (updateRectEncoding == EncodingZlib && !recordFromBeginning) {
786 // Here we cannot write Zlib-encoded rectangles because the
787 // decoder won't be able to reproduce zlib stream state.
788 if (!zlibWarningShown) {
789 System.out.println("Warning: Raw encoding will be used " +
790 "instead of Zlib in recorded session.");
791 zlibWarningShown = true;
792 }
793 rec.writeIntBE(EncodingRaw);
794 } else {
795 rec.writeIntBE(updateRectEncoding);
796 if (updateRectEncoding == EncodingTight && !recordFromBeginning &&
797 !tightWarningShown) {
798 System.out.println("Warning: Re-compressing Tight-encoded " +
799 "updates for session recording.");
800 tightWarningShown = true;
801 }
802 }
803 }
804
805 if (updateRectEncoding < 0 || updateRectEncoding > MaxNormalEncoding)
806 return;
807
808 if (updateRectX + updateRectW > framebufferWidth ||
809 updateRectY + updateRectH > framebufferHeight) {
810 throw new Exception("Framebuffer update rectangle too large: " +
811 updateRectW + "x" + updateRectH + " at (" +
812 updateRectX + "," + updateRectY + ")");
813 }
814 }
815
816 // Read CopyRect source X and Y.
817
818 int copyRectSrcX, copyRectSrcY;
819
820 void readCopyRect() throws IOException {
821 copyRectSrcX = readU16();
822 copyRectSrcY = readU16();
823
824 // If the session is being recorded:
825 if (rec != null) {
826 rec.writeShortBE(copyRectSrcX);
827 rec.writeShortBE(copyRectSrcY);
828 }
829 }
830
831
832 //
833 // Read a ServerCutText message
834 //
835
836 String readServerCutText() throws IOException {
837 skipBytes(3);
838 int len = readU32();
839 byte[] text = new byte[len];
840 readFully(text);
841 return new String(text);
842 }
843
844
845 //
846 // Read an integer in compact representation (1..3 bytes).
847 // Such format is used as a part of the Tight encoding.
848 // Also, this method records data if session recording is active and
849 // the viewer's recordFromBeginning variable is set to true.
850 //
851
852 int readCompactLen() throws IOException {
853 int[] portion = new int[3];
854 portion[0] = readU8();
855 int byteCount = 1;
856 int len = portion[0] & 0x7F;
857 if ((portion[0] & 0x80) != 0) {
858 portion[1] = readU8();
859 byteCount++;
860 len |= (portion[1] & 0x7F) << 7;
861 if ((portion[1] & 0x80) != 0) {
862 portion[2] = readU8();
863 byteCount++;
864 len |= (portion[2] & 0xFF) << 14;
865 }
866 }
867
868 if (rec != null && recordFromBeginning)
869 for (int i = 0; i < byteCount; i++)
870 rec.writeByte(portion[i]);
871
872 return len;
873 }
874
875
876 //
877 // Write a FramebufferUpdateRequest message
878 //
879
880 void writeFramebufferUpdateRequest(int x, int y, int w, int h,
881 boolean incremental)
882 throws IOException
883 {
884 byte[] b = new byte[10];
885
886 b[0] = (byte) FramebufferUpdateRequest;
887 b[1] = (byte) (incremental ? 1 : 0);
888 b[2] = (byte) ((x >> 8) & 0xff);
889 b[3] = (byte) (x & 0xff);
890 b[4] = (byte) ((y >> 8) & 0xff);
891 b[5] = (byte) (y & 0xff);
892 b[6] = (byte) ((w >> 8) & 0xff);
893 b[7] = (byte) (w & 0xff);
894 b[8] = (byte) ((h >> 8) & 0xff);
895 b[9] = (byte) (h & 0xff);
896
897 os.write(b);
898 }
899
900
901 //
902 // Write a SetPixelFormat message
903 //
904
905 void writeSetPixelFormat(int bitsPerPixel, int depth, boolean bigEndian,
906 boolean trueColour,
907 int redMax, int greenMax, int blueMax,
908 int redShift, int greenShift, int blueShift)
909 throws IOException
910 {
911 byte[] b = new byte[20];
912
913 b[0] = (byte) SetPixelFormat;
914 b[4] = (byte) bitsPerPixel;
915 b[5] = (byte) depth;
916 b[6] = (byte) (bigEndian ? 1 : 0);
917 b[7] = (byte) (trueColour ? 1 : 0);
918 b[8] = (byte) ((redMax >> 8) & 0xff);
919 b[9] = (byte) (redMax & 0xff);
920 b[10] = (byte) ((greenMax >> 8) & 0xff);
921 b[11] = (byte) (greenMax & 0xff);
922 b[12] = (byte) ((blueMax >> 8) & 0xff);
923 b[13] = (byte) (blueMax & 0xff);
924 b[14] = (byte) redShift;
925 b[15] = (byte) greenShift;
926 b[16] = (byte) blueShift;
927
928 os.write(b);
929 }
930
931
932 //
933 // Write a FixColourMapEntries message. The values in the red, green and
934 // blue arrays are from 0 to 65535.
935 //
936
937 void writeFixColourMapEntries(int firstColour, int nColours,
938 int[] red, int[] green, int[] blue)
939 throws IOException
940 {
941 byte[] b = new byte[6 + nColours * 6];
942
943 b[0] = (byte) FixColourMapEntries;
944 b[2] = (byte) ((firstColour >> 8) & 0xff);
945 b[3] = (byte) (firstColour & 0xff);
946 b[4] = (byte) ((nColours >> 8) & 0xff);
947 b[5] = (byte) (nColours & 0xff);
948
949 for (int i = 0; i < nColours; i++) {
950 b[6 + i * 6] = (byte) ((red[i] >> 8) & 0xff);
951 b[6 + i * 6 + 1] = (byte) (red[i] & 0xff);
952 b[6 + i * 6 + 2] = (byte) ((green[i] >> 8) & 0xff);
953 b[6 + i * 6 + 3] = (byte) (green[i] & 0xff);
954 b[6 + i * 6 + 4] = (byte) ((blue[i] >> 8) & 0xff);
955 b[6 + i * 6 + 5] = (byte) (blue[i] & 0xff);
956 }
957
958 os.write(b);
959 }
960
961
962 //
963 // Write a SetEncodings message
964 //
965
966 void writeSetEncodings(int[] encs, int len) throws IOException {
967 byte[] b = new byte[4 + 4 * len];
968
969 b[0] = (byte) SetEncodings;
970 b[2] = (byte) ((len >> 8) & 0xff);
971 b[3] = (byte) (len & 0xff);
972
973 for (int i = 0; i < len; i++) {
974 b[4 + 4 * i] = (byte) ((encs[i] >> 24) & 0xff);
975 b[5 + 4 * i] = (byte) ((encs[i] >> 16) & 0xff);
976 b[6 + 4 * i] = (byte) ((encs[i] >> 8) & 0xff);
977 b[7 + 4 * i] = (byte) (encs[i] & 0xff);
978 }
979
980 os.write(b);
981 }
982
983
984 //
985 // Write a ClientCutText message
986 //
987
988 void writeClientCutText(String text) throws IOException {
989 byte[] b = new byte[8 + text.length()];
990
991 b[0] = (byte) ClientCutText;
992 b[4] = (byte) ((text.length() >> 24) & 0xff);
993 b[5] = (byte) ((text.length() >> 16) & 0xff);
994 b[6] = (byte) ((text.length() >> 8) & 0xff);
995 b[7] = (byte) (text.length() & 0xff);
996
997 System.arraycopy(text.getBytes(), 0, b, 8, text.length());
998
999 os.write(b);
1000 }
1001
1002
1003 //
1004 // A buffer for putting pointer and keyboard events before being sent. This
1005 // is to ensure that multiple RFB events generated from a single Java Event
1006 // will all be sent in a single network packet. The maximum possible
1007 // length is 4 modifier down events, a single key event followed by 4
1008 // modifier up events i.e. 9 key events or 72 bytes.
1009 //
1010
1011 byte[] eventBuf = new byte[72];
1012 int eventBufLen;
1013
1014
1015 // Useful shortcuts for modifier masks.
1016
1017 final static int CTRL_MASK = InputEvent.CTRL_MASK;
1018 final static int SHIFT_MASK = InputEvent.SHIFT_MASK;
1019 final static int META_MASK = InputEvent.META_MASK;
1020 final static int ALT_MASK = InputEvent.ALT_MASK;
1021
1022
1023 //
1024 // Write a pointer event message. We may need to send modifier key events
1025 // around it to set the correct modifier state.
1026 //
1027
1028 int pointerMask = 0;
1029
1030 void writePointerEvent(MouseEvent evt) throws IOException {
1031 int modifiers = evt.getModifiers();
1032
1033 int mask2 = 2;
1034 int mask3 = 4;
1035 if (viewer.options.reverseMouseButtons2And3) {
1036 mask2 = 4;
1037 mask3 = 2;
1038 }
1039
1040 // Note: For some reason, AWT does not set BUTTON1_MASK on left
1041 // button presses. Here we think that it was the left button if
1042 // modifiers do not include BUTTON2_MASK or BUTTON3_MASK.
1043
1044 if (evt.getID() == MouseEvent.MOUSE_PRESSED) {
1045 if ((modifiers & InputEvent.BUTTON2_MASK) != 0) {
1046 pointerMask = mask2;
1047 modifiers &= ~ALT_MASK;
1048 } else if ((modifiers & InputEvent.BUTTON3_MASK) != 0) {
1049 pointerMask = mask3;
1050 modifiers &= ~META_MASK;
1051 } else {
1052 pointerMask = 1;
1053 }
1054 } else if (evt.getID() == MouseEvent.MOUSE_RELEASED) {
1055 pointerMask = 0;
1056 if ((modifiers & InputEvent.BUTTON2_MASK) != 0) {
1057 modifiers &= ~ALT_MASK;
1058 } else if ((modifiers & InputEvent.BUTTON3_MASK) != 0) {
1059 modifiers &= ~META_MASK;
1060 }
1061 }
1062
1063 eventBufLen = 0;
1064 writeModifierKeyEvents(modifiers);
1065
1066 int x = evt.getX();
1067 int y = evt.getY();
1068
1069 if (x < 0) x = 0;
1070 if (y < 0) y = 0;
1071
1072 eventBuf[eventBufLen++] = (byte) PointerEvent;
1073 eventBuf[eventBufLen++] = (byte) pointerMask;
1074 eventBuf[eventBufLen++] = (byte) ((x >> 8) & 0xff);
1075 eventBuf[eventBufLen++] = (byte) (x & 0xff);
1076 eventBuf[eventBufLen++] = (byte) ((y >> 8) & 0xff);
1077 eventBuf[eventBufLen++] = (byte) (y & 0xff);
1078
1079 //
1080 // Always release all modifiers after an "up" event
1081 //
1082
1083 if (pointerMask == 0) {
1084 writeModifierKeyEvents(0);
1085 }
1086
1087 os.write(eventBuf, 0, eventBufLen);
1088 }
1089
1090
1091 //
1092 // Write a key event message. We may need to send modifier key events
1093 // around it to set the correct modifier state. Also we need to translate
1094 // from the Java key values to the X keysym values used by the RFB protocol.
1095 //
1096
1097 void writeKeyEvent(KeyEvent evt) throws IOException {
1098
1099 int keyChar = evt.getKeyChar();
1100
1101 //
1102 // Ignore event if only modifiers were pressed.
1103 //
1104
1105 // Some JVMs return 0 instead of CHAR_UNDEFINED in getKeyChar().
1106 if (keyChar == 0)
1107 keyChar = KeyEvent.CHAR_UNDEFINED;
1108
1109 if (keyChar == KeyEvent.CHAR_UNDEFINED) {
1110 int code = evt.getKeyCode();
1111 if (code == KeyEvent.VK_CONTROL || code == KeyEvent.VK_SHIFT ||
1112 code == KeyEvent.VK_META || code == KeyEvent.VK_ALT)
1113 return;
1114 }
1115
1116 //
1117 // Key press or key release?
1118 //
1119
1120 boolean down = (evt.getID() == KeyEvent.KEY_PRESSED);
1121
1122 int key;
1123 if (evt.isActionKey()) {
1124
1125 //
1126 // An action key should be one of the following.
1127 // If not then just ignore the event.
1128 //
1129
1130 switch(evt.getKeyCode()) {
1131 case KeyEvent.VK_HOME: key = 0xff50; break;
1132 case KeyEvent.VK_LEFT: key = 0xff51; break;
1133 case KeyEvent.VK_UP: key = 0xff52; break;
1134 case KeyEvent.VK_RIGHT: key = 0xff53; break;
1135 case KeyEvent.VK_DOWN: key = 0xff54; break;
1136 case KeyEvent.VK_PAGE_UP: key = 0xff55; break;
1137 case KeyEvent.VK_PAGE_DOWN: key = 0xff56; break;
1138 case KeyEvent.VK_END: key = 0xff57; break;
1139 case KeyEvent.VK_INSERT: key = 0xff63; break;
1140 case KeyEvent.VK_F1: key = 0xffbe; break;
1141 case KeyEvent.VK_F2: key = 0xffbf; break;
1142 case KeyEvent.VK_F3: key = 0xffc0; break;
1143 case KeyEvent.VK_F4: key = 0xffc1; break;
1144 case KeyEvent.VK_F5: key = 0xffc2; break;
1145 case KeyEvent.VK_F6: key = 0xffc3; break;
1146 case KeyEvent.VK_F7: key = 0xffc4; break;
1147 case KeyEvent.VK_F8: key = 0xffc5; break;
1148 case KeyEvent.VK_F9: key = 0xffc6; break;
1149 case KeyEvent.VK_F10: key = 0xffc7; break;
1150 case KeyEvent.VK_F11: key = 0xffc8; break;
1151 case KeyEvent.VK_F12: key = 0xffc9; break;
1152 default:
1153 return;
1154 }
1155
1156 } else {
1157
1158 //
1159 // A "normal" key press. Ordinary ASCII characters go straight through.
1160 // For CTRL-<letter>, CTRL is sent separately so just send <letter>.
1161 // Backspace, tab, return, escape and delete have special keysyms.
1162 // Anything else we ignore.
1163 //
1164
1165 key = keyChar;
1166
1167 if (key < 0x20) {
1168 if (evt.isControlDown()) {
1169 key += 0x60;
1170 } else {
1171 switch(key) {
1172 case KeyEvent.VK_BACK_SPACE: key = 0xff08; break;
1173 case KeyEvent.VK_TAB: key = 0xff09; break;
1174 case KeyEvent.VK_ENTER: key = 0xff0d; break;
1175 case KeyEvent.VK_ESCAPE: key = 0xff1b; break;
1176 }
1177 }
1178 } else if (key == 0x7f) {
1179 // Delete
1180 key = 0xffff;
1181 } else if (key > 0xff) {
1182 // JDK1.1 on X incorrectly passes some keysyms straight through,
1183 // so we do too. JDK1.1.4 seems to have fixed this.
1184 // The keysyms passed are 0xff00 .. XK_BackSpace .. XK_Delete
1185 // Also, we pass through foreign currency keysyms (0x20a0..0x20af).
1186 if ((key < 0xff00 || key > 0xffff) &&
1187 !(key >= 0x20a0 && key <= 0x20af))
1188 return;
1189 }
1190 }
1191
1192 // Fake keyPresses for keys that only generates keyRelease events
1193 if ((key == 0xe5) || (key == 0xc5) || // XK_aring / XK_Aring
1194 (key == 0xe4) || (key == 0xc4) || // XK_adiaeresis / XK_Adiaeresis
1195 (key == 0xf6) || (key == 0xd6) || // XK_odiaeresis / XK_Odiaeresis
1196 (key == 0xa7) || (key == 0xbd) || // XK_section / XK_onehalf
1197 (key == 0xa3)) { // XK_sterling
1198 // Make sure we do not send keypress events twice on platforms
1199 // with correct JVMs (those that actually report KeyPress for all
1200 // keys)
1201 if (down)
1202 brokenKeyPressed = true;
1203
1204 if (!down && !brokenKeyPressed) {
1205 // We've got a release event for this key, but haven't received
1206 // a press. Fake it.
1207 eventBufLen = 0;
1208 writeModifierKeyEvents(evt.getModifiers());
1209 writeKeyEvent(key, true);
1210 os.write(eventBuf, 0, eventBufLen);
1211 }
1212
1213 if (!down)
1214 brokenKeyPressed = false;
1215 }
1216
1217 eventBufLen = 0;
1218 writeModifierKeyEvents(evt.getModifiers());
1219 writeKeyEvent(key, down);
1220
1221 // Always release all modifiers after an "up" event
1222 if (!down)
1223 writeModifierKeyEvents(0);
1224
1225 os.write(eventBuf, 0, eventBufLen);
1226 }
1227
1228
1229 //
1230 // Add a raw key event with the given X keysym to eventBuf.
1231 //
1232
1233 void writeKeyEvent(int keysym, boolean down) {
1234 eventBuf[eventBufLen++] = (byte) KeyboardEvent;
1235 eventBuf[eventBufLen++] = (byte) (down ? 1 : 0);
1236 eventBuf[eventBufLen++] = (byte) 0;
1237 eventBuf[eventBufLen++] = (byte) 0;
1238 eventBuf[eventBufLen++] = (byte) ((keysym >> 24) & 0xff);
1239 eventBuf[eventBufLen++] = (byte) ((keysym >> 16) & 0xff);
1240 eventBuf[eventBufLen++] = (byte) ((keysym >> 8) & 0xff);
1241 eventBuf[eventBufLen++] = (byte) (keysym & 0xff);
1242 }
1243
1244
1245 //
1246 // Write key events to set the correct modifier state.
1247 //
1248
1249 int oldModifiers = 0;
1250
1251 void writeModifierKeyEvents(int newModifiers) {
1252 if ((newModifiers & CTRL_MASK) != (oldModifiers & CTRL_MASK))
1253 writeKeyEvent(0xffe3, (newModifiers & CTRL_MASK) != 0);
1254
1255 if ((newModifiers & SHIFT_MASK) != (oldModifiers & SHIFT_MASK))
1256 writeKeyEvent(0xffe1, (newModifiers & SHIFT_MASK) != 0);
1257
1258 if ((newModifiers & META_MASK) != (oldModifiers & META_MASK))
1259 writeKeyEvent(0xffe7, (newModifiers & META_MASK) != 0);
1260
1261 if ((newModifiers & ALT_MASK) != (oldModifiers & ALT_MASK))
1262 writeKeyEvent(0xffe9, (newModifiers & ALT_MASK) != 0);
1263
1264 oldModifiers = newModifiers;
1265 }
1266
1267
1268 //
1269 // Enable continuous updates for the specified area of the screen (but
1270 // only if EnableContinuousUpdates message is supported by the server).
1271 //
1272
1273 void tryEnableContinuousUpdates(int x, int y, int w, int h)
1274 throws IOException
1275 {
1276 if (!clientMsgCaps.isEnabled(EnableContinuousUpdates)) {
1277 System.out.println("Continuous updates not supported by the server");
1278 return;
1279 }
1280
1281 if (continuousUpdatesActive) {
1282 System.out.println("Continuous updates already active");
1283 return;
1284 }
1285
1286 byte[] b = new byte[10];
1287
1288 b[0] = (byte) EnableContinuousUpdates;
1289 b[1] = (byte) 1; // enable
1290 b[2] = (byte) ((x >> 8) & 0xff);
1291 b[3] = (byte) (x & 0xff);
1292 b[4] = (byte) ((y >> 8) & 0xff);
1293 b[5] = (byte) (y & 0xff);
1294 b[6] = (byte) ((w >> 8) & 0xff);
1295 b[7] = (byte) (w & 0xff);
1296 b[8] = (byte) ((h >> 8) & 0xff);
1297 b[9] = (byte) (h & 0xff);
1298
1299 os.write(b);
1300
1301 continuousUpdatesActive = true;
1302 System.out.println("Continuous updates activated");
1303 }
1304
1305
1306 //
1307 // Disable continuous updates (only if EnableContinuousUpdates message
1308 // is supported by the server).
1309 //
1310
1311 void tryDisableContinuousUpdates() throws IOException
1312 {
1313 if (!clientMsgCaps.isEnabled(EnableContinuousUpdates)) {
1314 System.out.println("Continuous updates not supported by the server");
1315 return;
1316 }
1317
1318 if (!continuousUpdatesActive) {
1319 System.out.println("Continuous updates already disabled");
1320 return;
1321 }
1322
1323 if (continuousUpdatesEnding)
1324 return;
1325
1326 byte[] b = { (byte)EnableContinuousUpdates, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
1327 os.write(b);
1328
1329 if (!serverMsgCaps.isEnabled(EndOfContinuousUpdates)) {
1330 // If the server did not advertise support for the
1331 // EndOfContinuousUpdates message (should not normally happen
1332 // when EnableContinuousUpdates is supported), then we clear
1333 // 'continuousUpdatesActive' variable immediately. Normally,
1334 // it will be reset on receiving EndOfContinuousUpdates message
1335 // from the server.
1336 continuousUpdatesActive = false;
1337 } else {
1338 // Indicate that we are waiting for EndOfContinuousUpdates.
1339 continuousUpdatesEnding = true;
1340 }
1341 }
1342
1343
1344 //
1345 // Process EndOfContinuousUpdates message received from the server.
1346 //
1347
1348 void endOfContinuousUpdates()
1349 {
1350 continuousUpdatesActive = false;
1351 continuousUpdatesEnding = false;
1352 }
1353
1354
1355 //
1356 // Check if continuous updates are in effect.
1357 //
1358
1359 boolean continuousUpdatesAreActive()
1360 {
1361 return continuousUpdatesActive;
1362 }
1363
Constantin Kaplinskyf7cb2bf2008-05-27 08:38:28 +00001364 /**
1365 * Send a rectangle selection to be treated as video by the server (but
1366 * only if VideoRectangleSelection message is supported by the server).
1367 * @param rect specifies coordinates and size of the rectangule.
1368 * @throws java.io.IOException
1369 */
1370 void trySendVideoSelection(Rectangle rect) throws IOException
1371 {
1372 if (!clientMsgCaps.isEnabled(VideoRectangleSelection)) {
1373 System.out.println("Video area selection is not supported by the server");
1374 return;
1375 }
1376
Constantin Kaplinsky4f652852008-09-05 02:41:15 +00001377 // Send zero coordinates if the rectangle is empty.
1378 if (rect.isEmpty()) {
1379 rect = new Rectangle();
1380 }
1381
Constantin Kaplinskyf7cb2bf2008-05-27 08:38:28 +00001382 int x = rect.x;
1383 int y = rect.y;
1384 int w = rect.width;
1385 int h = rect.height;
1386
1387 byte[] b = new byte[10];
1388
1389 b[0] = (byte) VideoRectangleSelection;
1390 b[1] = (byte) 0; // reserved
1391 b[2] = (byte) ((x >> 8) & 0xff);
1392 b[3] = (byte) (x & 0xff);
1393 b[4] = (byte) ((y >> 8) & 0xff);
1394 b[5] = (byte) (y & 0xff);
1395 b[6] = (byte) ((w >> 8) & 0xff);
1396 b[7] = (byte) (w & 0xff);
1397 b[8] = (byte) ((h >> 8) & 0xff);
1398 b[9] = (byte) (h & 0xff);
1399
1400 os.write(b);
1401
1402 System.out.println("Video rectangle selection message sent");
1403 }
1404
Constantin Kaplinsky2844fd52008-04-14 08:02:25 +00001405
1406 //
1407 // Compress and write the data into the recorded session file. This
1408 // method assumes the recording is on (rec != null).
1409 //
1410
1411 void recordCompressedData(byte[] data, int off, int len) throws IOException {
1412 Deflater deflater = new Deflater();
1413 deflater.setInput(data, off, len);
1414 int bufSize = len + len / 100 + 12;
1415 byte[] buf = new byte[bufSize];
1416 deflater.finish();
1417 int compressedSize = deflater.deflate(buf);
1418 recordCompactLen(compressedSize);
1419 rec.write(buf, 0, compressedSize);
1420 }
1421
1422 void recordCompressedData(byte[] data) throws IOException {
1423 recordCompressedData(data, 0, data.length);
1424 }
1425
1426 //
1427 // Write an integer in compact representation (1..3 bytes) into the
1428 // recorded session file. This method assumes the recording is on
1429 // (rec != null).
1430 //
1431
1432 void recordCompactLen(int len) throws IOException {
1433 byte[] buf = new byte[3];
1434 int bytes = 0;
1435 buf[bytes++] = (byte)(len & 0x7F);
1436 if (len > 0x7F) {
1437 buf[bytes-1] |= 0x80;
1438 buf[bytes++] = (byte)(len >> 7 & 0x7F);
1439 if (len > 0x3FFF) {
1440 buf[bytes-1] |= 0x80;
1441 buf[bytes++] = (byte)(len >> 14 & 0xFF);
1442 }
1443 }
1444 rec.write(buf, 0, bytes);
1445 }
1446
1447 public void startTiming() {
1448 timing = true;
1449
1450 // Carry over up to 1s worth of previous rate for smoothing.
1451
1452 if (timeWaitedIn100us > 10000) {
1453 timedKbits = timedKbits * 10000 / timeWaitedIn100us;
1454 timeWaitedIn100us = 10000;
1455 }
1456 }
1457
1458 public void stopTiming() {
1459 timing = false;
1460 if (timeWaitedIn100us < timedKbits/2)
1461 timeWaitedIn100us = timedKbits/2; // upper limit 20Mbit/s
1462 }
1463
1464 public long kbitsPerSecond() {
1465 return timedKbits * 10000 / timeWaitedIn100us;
1466 }
1467
1468 public long timeWaited() {
1469 return timeWaitedIn100us;
1470 }
1471
1472 //
1473 // Methods for reading data via our DataInputStream member variable (is).
1474 //
1475 // In addition to reading data, the readFully() methods updates variables
1476 // used to estimate data throughput.
1477 //
1478
1479 public void readFully(byte b[]) throws IOException {
1480 readFully(b, 0, b.length);
1481 }
1482
1483 public void readFully(byte b[], int off, int len) throws IOException {
1484 long before = 0;
1485 if (timing)
1486 before = System.currentTimeMillis();
1487
1488 is.readFully(b, off, len);
1489
1490 if (timing) {
1491 long after = System.currentTimeMillis();
1492 long newTimeWaited = (after - before) * 10;
1493 int newKbits = len * 8 / 1000;
1494
1495 // limit rate to between 10kbit/s and 40Mbit/s
1496
1497 if (newTimeWaited > newKbits*1000) newTimeWaited = newKbits*1000;
1498 if (newTimeWaited < newKbits/4) newTimeWaited = newKbits/4;
1499
1500 timeWaitedIn100us += newTimeWaited;
1501 timedKbits += newKbits;
1502 }
1503
1504 numBytesRead += len;
1505 }
1506
1507 final int available() throws IOException {
1508 return is.available();
1509 }
1510
1511 // FIXME: DataInputStream::skipBytes() is not guaranteed to skip
1512 // exactly n bytes. Probably we don't want to use this method.
1513 final int skipBytes(int n) throws IOException {
1514 int r = is.skipBytes(n);
1515 numBytesRead += r;
1516 return r;
1517 }
1518
1519 final int readU8() throws IOException {
1520 int r = is.readUnsignedByte();
1521 numBytesRead++;
1522 return r;
1523 }
1524
1525 final int readU16() throws IOException {
1526 int r = is.readUnsignedShort();
1527 numBytesRead += 2;
1528 return r;
1529 }
1530
1531 final int readU32() throws IOException {
1532 int r = is.readInt();
1533 numBytesRead += 4;
1534 return r;
1535 }
1536}
1537