add libvncserver
[presencevnc] / libvnc / libvncserver / scale.c
1 /*
2  * scale.c - deal with server-side scaling.
3  */
4
5 /*
6  *  Copyright (C) 2005 Rohit Kumar, Johannes E. Schindelin
7  *  Copyright (C) 2002 RealVNC Ltd.
8  *  OSXvnc Copyright (C) 2001 Dan McGuirk <mcguirk@incompleteness.net>.
9  *  Original Xvnc code Copyright (C) 1999 AT&T Laboratories Cambridge.  
10  *  All Rights Reserved.
11  *
12  *  This is free software; you can redistribute it and/or modify
13  *  it under the terms of the GNU General Public License as published by
14  *  the Free Software Foundation; either version 2 of the License, or
15  *  (at your option) any later version.
16  *
17  *  This software is distributed in the hope that it will be useful,
18  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
19  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20  *  GNU General Public License for more details.
21  *
22  *  You should have received a copy of the GNU General Public License
23  *  along with this software; if not, write to the Free Software
24  *  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307,
25  *  USA.
26  */
27
28 #ifdef __STRICT_ANSI__
29 #define _BSD_SOURCE
30 #endif
31 #include <string.h>
32 #include <rfb/rfb.h>
33 #include <rfb/rfbregion.h>
34 #include "private.h"
35
36 #ifdef LIBVNCSERVER_HAVE_FCNTL_H
37 #include <fcntl.h>
38 #endif
39
40 #ifdef WIN32
41 #define write(sock,buf,len) send(sock,buf,len,0)
42 #else
43 #ifdef LIBVNCSERVER_HAVE_UNISTD_H
44 #include <unistd.h>
45 #endif
46 #include <pwd.h>
47 #ifdef LIBVNCSERVER_HAVE_SYS_SOCKET_H
48 #include <sys/socket.h>
49 #endif
50 #ifdef LIBVNCSERVER_HAVE_NETINET_IN_H
51 #include <netinet/in.h>
52 #include <netinet/tcp.h>
53 #include <arpa/inet.h>
54 #endif
55 #endif
56
57 #ifdef CORBA
58 #include <vncserverctrl.h>
59 #endif
60
61 #ifdef DEBUGPROTO
62 #undef DEBUGPROTO
63 #define DEBUGPROTO(x) x
64 #else
65 #define DEBUGPROTO(x)
66 #endif
67
68 /****************************/
69 #define CEIL(x)  ( (double) ((int) (x)) == (x) ? \
70         (double) ((int) (x)) : (double) ((int) (x) + 1) )
71 #define FLOOR(x) ( (double) ((int) (x)) )
72
73
74 int ScaleX(rfbScreenInfoPtr from, rfbScreenInfoPtr to, int x)
75 {
76     if ((from==to) || (from==NULL) || (to==NULL)) return x;
77     return ((int)(((double) x / (double)from->width) * (double)to->width ));
78 }
79
80 int ScaleY(rfbScreenInfoPtr from, rfbScreenInfoPtr to, int y)
81 {
82     if ((from==to) || (from==NULL) || (to==NULL)) return y;
83     return ((int)(((double) y / (double)from->height) * (double)to->height ));
84 }
85
86 /* So, all of the encodings point to the ->screen->frameBuffer,
87  * We need to change this!
88  */
89 void rfbScaledCorrection(rfbScreenInfoPtr from, rfbScreenInfoPtr to, int *x, int *y, int *w, int *h, char *function)
90 {
91     double x1,y1,w1,h1, x2, y2, w2, h2;
92     double scaleW = ((double) to->width) / ((double) from->width);
93     double scaleH = ((double) to->height) / ((double) from->height);
94
95
96     /*
97      * rfbLog("rfbScaledCorrection(%p -> %p, %dx%d->%dx%d (%dXx%dY-%dWx%dH)\n",
98      * from, to, from->width, from->height, to->width, to->height, *x, *y, *w, *h);
99      */
100
101     /* If it's the original framebuffer... */
102     if (from==to) return;
103
104     x1 = ((double) *x) * scaleW;
105     y1 = ((double) *y) * scaleH;
106     w1 = ((double) *w) * scaleW;
107     h1 = ((double) *h) * scaleH;
108
109
110     /*cast from double to int is same as "*x = floor(x1);" */
111     x2 = FLOOR(x1);
112     y2 = FLOOR(y1);
113
114     /* include into W and H the jitter of scaling X and Y */
115     w2 = CEIL(w1 + ( x1 - x2 ));
116     h2 = CEIL(h1 + ( y1 - y2 ));
117
118     /*
119      * rfbLog("%s (%dXx%dY-%dWx%dH  ->  %fXx%fY-%fWx%fH) {%dWx%dH -> %dWx%dH}\n",
120      *    function, *x, *y, *w, *h, x2, y2, w2, h2,
121      *    from->width, from->height, to->width, to->height);
122      */
123
124     /* simulate ceil() without math library */
125     *x = (int)x2;
126     *y = (int)y2;
127     *w = (int)w2;
128     *h = (int)h2;
129
130     /* Small changes for a thumbnail may be scaled to zero */
131     if (*w==0) (*w)++;
132     if (*h==0) (*h)++;
133     /* scaling from small to big may overstep the size a bit */
134     if (*x+*w > to->width)  *w=to->width - *x;
135     if (*y+*h > to->height) *h=to->height - *y;
136 }
137
138 void rfbScaledScreenUpdateRect(rfbScreenInfoPtr screen, rfbScreenInfoPtr ptr, int x0, int y0, int w0, int h0)
139 {
140     int x,y,w,v,z;
141     int x1, y1, w1, h1;
142     int bitsPerPixel, bytesPerPixel, bytesPerLine, areaX, areaY, area2;
143     unsigned char *srcptr, *dstptr;
144
145     /* Nothing to do!!! */
146     if (screen==ptr) return;
147
148     x1 = x0;
149     y1 = y0;
150     w1 = w0;
151     h1 = h0;
152
153     rfbScaledCorrection(screen, ptr, &x1, &y1, &w1, &h1, "rfbScaledScreenUpdateRect");
154     x0 = ScaleX(ptr, screen, x1);
155     y0 = ScaleY(ptr, screen, y1);
156     w0 = ScaleX(ptr, screen, w1);
157     h0 = ScaleY(ptr, screen, h1);
158
159     bitsPerPixel = screen->bitsPerPixel;
160     bytesPerPixel = bitsPerPixel / 8;
161     bytesPerLine = w1 * bytesPerPixel;
162     srcptr = (unsigned char *)(screen->frameBuffer +
163      (y0 * screen->paddedWidthInBytes + x0 * bytesPerPixel));
164     dstptr = (unsigned char *)(ptr->frameBuffer +
165      ( y1 * ptr->paddedWidthInBytes + x1 * bytesPerPixel));
166     /* The area of the source framebuffer for each destination pixel */
167     areaX = ScaleX(ptr,screen,1);
168     areaY = ScaleY(ptr,screen,1);
169     area2 = areaX*areaY;
170
171
172     /* Ensure that we do not go out of bounds */
173     if ((x1+w1) > (ptr->width))
174     {
175       if (x1==0) w1=ptr->width; else x1 = ptr->width - w1;
176     }
177     if ((y1+h1) > (ptr->height))
178     {
179       if (y1==0) h1=ptr->height; else y1 = ptr->height - h1;
180     }
181     /*
182      * rfbLog("rfbScaledScreenUpdateRect(%dXx%dY-%dWx%dH  ->  %dXx%dY-%dWx%dH <%dx%d>) {%dWx%dH -> %dWx%dH} 0x%p\n",
183      *    x0, y0, w0, h0, x1, y1, w1, h1, areaX, areaY,
184      *    screen->width, screen->height, ptr->width, ptr->height, ptr->frameBuffer);
185      */
186
187     if (screen->serverFormat.trueColour) { /* Blend neighbouring pixels together */
188       unsigned char *srcptr2;
189       unsigned long pixel_value, red, green, blue;
190       unsigned int redShift = screen->serverFormat.redShift;
191       unsigned int greenShift = screen->serverFormat.greenShift;
192       unsigned int blueShift = screen->serverFormat.blueShift;
193       unsigned long redMax = screen->serverFormat.redMax;
194       unsigned long greenMax = screen->serverFormat.greenMax;
195       unsigned long blueMax = screen->serverFormat.blueMax;
196
197      /* for each *destination* pixel... */
198      for (y = 0; y < h1; y++) {
199        for (x = 0; x < w1; x++) {
200          red = green = blue = 0;
201          /* Get the totals for rgb from the source grid... */
202          for (w = 0; w < areaX; w++) {
203            for (v = 0; v < areaY; v++) {
204              srcptr2 = &srcptr[(((x * areaX) + w) * bytesPerPixel) +
205                                (v * screen->paddedWidthInBytes)];
206              pixel_value = 0;
207
208
209              switch (bytesPerPixel) {
210              case 4: pixel_value = *((unsigned int *)srcptr2);   break;
211              case 2: pixel_value = *((unsigned short *)srcptr2); break;
212              case 1: pixel_value = *((unsigned char *)srcptr2);  break;
213              default:
214                /* fixme: endianess problem? */
215                for (z = 0; z < bytesPerPixel; z++)
216                  pixel_value += (srcptr2[z] << (8 * z));
217                 break;
218               }
219               /*
220               srcptr2 += bytesPerPixel;
221               */
222
223             red += ((pixel_value >> redShift) & redMax);
224             green += ((pixel_value >> greenShift) & greenMax);
225             blue += ((pixel_value >> blueShift) & blueMax);
226
227            }
228          }
229          /* We now have a total for all of the colors, find the average! */
230          red /= area2;
231          green /= area2;
232          blue /= area2;
233           /* Stuff the new value back into memory */
234          pixel_value = ((red & redMax) << redShift) | ((green & greenMax) << greenShift) | ((blue & blueMax) << blueShift);
235
236          switch (bytesPerPixel) {
237          case 4: *((unsigned int *)dstptr)   = (unsigned int)   pixel_value; break;
238          case 2: *((unsigned short *)dstptr) = (unsigned short) pixel_value; break;
239          case 1: *((unsigned char *)dstptr)  = (unsigned char)  pixel_value; break;
240          default:
241            /* fixme: endianess problem? */
242            for (z = 0; z < bytesPerPixel; z++)
243              dstptr[z]=(pixel_value >> (8 * z)) & 0xff;
244             break;
245           }
246           dstptr += bytesPerPixel;
247        }
248        srcptr += (screen->paddedWidthInBytes * areaY);
249        dstptr += (ptr->paddedWidthInBytes - bytesPerLine);
250      }
251    } else
252    { /* Not truecolour, so we can't blend. Just use the top-left pixel instead */
253      for (y = y1; y < (y1+h1); y++) {
254        for (x = x1; x < (x1+w1); x++)
255          memcpy (&ptr->frameBuffer[(y *ptr->paddedWidthInBytes) + (x * bytesPerPixel)],
256                  &screen->frameBuffer[(y * areaY * screen->paddedWidthInBytes) + (x *areaX * bytesPerPixel)], bytesPerPixel);
257      }
258   }
259 }
260
261 void rfbScaledScreenUpdate(rfbScreenInfoPtr screen, int x1, int y1, int x2, int y2)
262 {
263     /* ok, now the task is to update each and every scaled version of the framebuffer
264      * and we only have to do this for this specific changed rectangle!
265      */
266     rfbScreenInfoPtr ptr;
267     int count=0;
268
269     /* We don't point to cl->screen as it is the original */
270     for (ptr=screen->scaledScreenNext;ptr!=NULL;ptr=ptr->scaledScreenNext)
271     {
272         /* Only update if it has active clients... */
273         if (ptr->scaledScreenRefCount>0)
274         {
275           rfbScaledScreenUpdateRect(screen, ptr, x1, y1, x2-x1, y2-y1);
276           count++;
277         }
278     }
279 }
280
281 /* Create a new scaled version of the framebuffer */
282 rfbScreenInfoPtr rfbScaledScreenAllocate(rfbClientPtr cl, int width, int height)
283 {
284     rfbScreenInfoPtr ptr;
285     ptr = malloc(sizeof(rfbScreenInfo));
286     if (ptr!=NULL)
287     {
288         /* copy *everything* (we don't use most of it, but just in case) */
289         memcpy(ptr, cl->screen, sizeof(rfbScreenInfo));
290         ptr->width = width;
291         ptr->height = height;
292         ptr->paddedWidthInBytes = (ptr->bitsPerPixel/8)*ptr->width;
293
294         /* Need to by multiples of 4 for Sparc systems */
295         ptr->paddedWidthInBytes += (ptr->paddedWidthInBytes % 4);
296
297         /* Reset the reference count to 0! */
298         ptr->scaledScreenRefCount = 0;
299
300         ptr->sizeInBytes = ptr->paddedWidthInBytes * ptr->height;
301         ptr->serverFormat = cl->screen->serverFormat;
302
303         ptr->frameBuffer = malloc(ptr->sizeInBytes);
304         if (ptr->frameBuffer!=NULL)
305         {
306             /* Reset to a known condition: scale the entire framebuffer */
307             rfbScaledScreenUpdateRect(cl->screen, ptr, 0, 0, cl->screen->width, cl->screen->height);
308             /* Now, insert into the chain */
309             LOCK(cl->updateMutex);
310             ptr->scaledScreenNext = cl->screen->scaledScreenNext;
311             cl->screen->scaledScreenNext = ptr;
312             UNLOCK(cl->updateMutex);
313         }
314         else
315         {
316             /* Failed to malloc the new frameBuffer, cleanup */
317             free(ptr);
318             ptr=NULL;
319         }
320     }
321     return ptr;
322 }
323
324 /* Find an active scaled version of the framebuffer
325  * TODO: implement a refcount per scaled screen to prevent
326  * unreferenced scaled screens from hanging around
327  */
328 rfbScreenInfoPtr rfbScalingFind(rfbClientPtr cl, int width, int height)
329 {
330     rfbScreenInfoPtr ptr;
331     /* include the original in the search (ie: fine 1:1 scaled version of the frameBuffer) */
332     for (ptr=cl->screen; ptr!=NULL; ptr=ptr->scaledScreenNext)
333     {
334         if ((ptr->width==width) && (ptr->height==height))
335             return ptr;
336     }
337     return NULL;
338 }
339
340 /* Future needs "scale to 320x240, as that's the client's screen size */
341 void rfbScalingSetup(rfbClientPtr cl, int width, int height)
342 {
343     rfbScreenInfoPtr ptr;
344
345     ptr = rfbScalingFind(cl,width,height);
346     if (ptr==NULL)
347         ptr = rfbScaledScreenAllocate(cl,width,height);
348     /* Now, there is a new screen available (if ptr is not NULL) */
349     if (ptr!=NULL)
350     {
351         /* Update it! */
352         if (ptr->scaledScreenRefCount<1)
353             rfbScaledScreenUpdateRect(cl->screen, ptr, 0, 0, cl->screen->width, cl->screen->height);
354         /*
355          * rfbLog("Taking one from %dx%d-%d and adding it to %dx%d-%d\n",
356          *    cl->scaledScreen->width, cl->scaledScreen->height,
357          *    cl->scaledScreen->scaledScreenRefCount,
358          *    ptr->width, ptr->height, ptr->scaledScreenRefCount);
359          */
360
361         LOCK(cl->updateMutex);
362         cl->scaledScreen->scaledScreenRefCount--;
363         ptr->scaledScreenRefCount++;
364         cl->scaledScreen=ptr;
365         cl->newFBSizePending = TRUE;
366         UNLOCK(cl->updateMutex);
367
368         rfbLog("Scaling to %dx%d (refcount=%d)\n",width,height,ptr->scaledScreenRefCount);
369     }
370     else
371         rfbLog("Scaling to %dx%d failed, leaving things alone\n",width,height);
372 }
373
374 int rfbSendNewScaleSize(rfbClientPtr cl)
375 {
376     /* if the client supports newFBsize Encoding, use it */
377     if (cl->useNewFBSize && cl->newFBSizePending)
378         return FALSE;
379
380     LOCK(cl->updateMutex);
381     cl->newFBSizePending = FALSE;
382     UNLOCK(cl->updateMutex);
383
384     if (cl->PalmVNC==TRUE)
385     {
386         rfbPalmVNCReSizeFrameBufferMsg pmsg;
387         pmsg.type = rfbPalmVNCReSizeFrameBuffer;
388         pmsg.pad1 = 0;
389         pmsg.desktop_w = Swap16IfLE(cl->screen->width);
390         pmsg.desktop_h = Swap16IfLE(cl->screen->height);
391         pmsg.buffer_w  = Swap16IfLE(cl->scaledScreen->width);
392         pmsg.buffer_h  = Swap16IfLE(cl->scaledScreen->height);
393         pmsg.pad2 = 0;
394
395         rfbLog("Sending a response to a PalmVNC style frameuffer resize event (%dx%d)\n", cl->scaledScreen->width, cl->scaledScreen->height);
396         if (rfbWriteExact(cl, (char *)&pmsg, sz_rfbPalmVNCReSizeFrameBufferMsg) < 0) {
397             rfbLogPerror("rfbNewClient: write");
398             rfbCloseClient(cl);
399             rfbClientConnectionGone(cl);
400             return FALSE;
401         }
402     }
403     else
404     {
405         rfbResizeFrameBufferMsg        rmsg;
406         rmsg.type = rfbResizeFrameBuffer;
407         rmsg.pad1=0;
408         rmsg.framebufferWidth  = Swap16IfLE(cl->scaledScreen->width);
409         rmsg.framebufferHeigth = Swap16IfLE(cl->scaledScreen->height);
410         rfbLog("Sending a response to a UltraVNC style frameuffer resize event (%dx%d)\n", cl->scaledScreen->width, cl->scaledScreen->height);
411         if (rfbWriteExact(cl, (char *)&rmsg, sz_rfbResizeFrameBufferMsg) < 0) {
412             rfbLogPerror("rfbNewClient: write");
413             rfbCloseClient(cl);
414             rfbClientConnectionGone(cl);
415             return FALSE;
416         }
417     }
418     return TRUE;
419 }
420 /****************************/