xref: /netbsd-src/sys/arch/macppc/dev/pbms.c (revision 404fbe5fb94ca1e054339640cabb2801ce52dd30)
1 /* $Id: pbms.c,v 1.7 2007/10/17 19:55:19 garbled Exp $ */
2 
3 /*
4  * Copyright (c) 2005, Johan Wall�n
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions are
9  * met:
10  *
11  *   1. Redistributions of source code must retain the above copyright
12  *      notice, this list of conditions and the following disclaimer.
13  *
14  *   2. Redistributions in binary form must reproduce the above
15  *      copyright notice, this list of conditions and the following
16  *      disclaimer in the documentation and/or other materials provided
17  *      with the distribution.
18  *
19  *   3. The name of the copyright holder may not be used to endorse or
20  *      promote products derived from this software without specific
21  *      prior written permission.
22  *
23  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER "AS IS" AND ANY
24  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
25  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
26  * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER BE
27  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
28  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
29  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
30  * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
31  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
32  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
33  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
34  */
35 
36 /*
37  * The pbms driver provides support for the trackpad on new (post
38  * February 2005) Apple PowerBooks (and iBooks?) that are not standard
39  * USB HID mice.
40  */
41 
42 /*
43  * The protocol (that is, the interpretation of the data generated by
44  * the trackpad) is taken from the Linux appletouch driver version
45  * 0.08 by Johannes Berg, Stelian Pop and Frank Arnold.  The method
46  * used to detect fingers on the trackpad is also taken from that
47  * driver.
48  */
49 
50 /*
51  * To add support for other devices using the same protocol, add an
52  * entry to the pbms_devices table below.  See the comments for
53  * pbms_devices and struct pbms_devs.
54  */
55 
56 /*
57  * PROTOCOL:
58  *
59  * The driver transfers continuously 81 byte events.  The last byte is
60  * 1 if the button is pressed, and is 0 otherwise. Of the remaining
61  * bytes, 26 + 16 = 42 are sensors detecting pressure in the X or
62  * horizontal, and Y or vertical directions, respectively.  On 12 and
63  * 15 inch PowerBooks, only the 16 first sensors in the X-direction
64  * are used. In the X-direction, the sensors correspond to byte
65  * positions
66  *
67  *   2, 7, 12, 17, 22, 27, 32, 37, 4, 9, 14, 19, 24, 29, 34, 39, 42,
68  *   47, 52, 57, 62, 67, 72, 77, 44 and 49;
69  *
70  * in the Y direction, the sensors correspond to byte positions
71  *
72  *   1, 6, 11, 16, 21, 26, 31, 36, 3, 8, 13, 18, 23, 28, 33 and 38.
73  *
74  * The change in the sensor values over time is more interesting than
75  * their absolute values: if the pressure increases, we know that the
76  * finger has just moved there.
77  *
78  * We keep track of the previous sample (of sensor values in the X and
79  * Y directions) and the accumulated change for each sensor.  When we
80  * receive a new sample, we add the difference of the new sensor value
81  * and the old value to the accumulated change.  If the accumulator
82  * becomes negative, we set it to zero.  The effect is that the
83  * accumulator is large for sensors whose pressure has recently
84  * increased.  If there is little change in pressure (or if the
85  * pressure decreases), the accumulator drifts back to zero.
86  *
87  * Since there is some fluctuations, we ignore accumulator values
88  * below a threshold.  The raw finger position is computed as a
89  * weighted average of the other sensors (the weights are the
90  * accumulated changes).
91  *
92  * For smoothing, we keep track of the previous raw finger position,
93  * and the virtual position reported to wsmouse.  The new raw position
94  * is computed as a weighted average of the old raw position and the
95  * computed raw position.  Since this still generates some noise, we
96  * compute a new virtual position as a weighted average of the previous
97  * virtual position and the new raw position.  The weights are
98  * controlled by the raw change and a noise parameter.  The position
99  * is reported as a relative position.
100  */
101 
102 /*
103  * TODO:
104  *
105  * Add support for other drivers of the same type.
106  *
107  * Add support for tapping and two-finger scrolling?  The
108  * implementation already detects two fingers, so this should be
109  * relatively easy.
110  *
111  * Implement some of the mouse ioctls?
112  *
113  * Take care of the XXXs.
114  *
115  */
116 
117 #include <sys/cdefs.h>
118 
119 #include <sys/param.h>
120 #include <sys/device.h>
121 #include <sys/errno.h>
122 
123 #include <sys/ioctl.h>
124 #include <sys/systm.h>
125 #include <sys/tty.h>
126 
127 #include <dev/usb/usb.h>
128 #include <dev/usb/usbdi.h>
129 #include <dev/usb/usbdevs.h>
130 #include <dev/usb/uhidev.h>
131 
132 #include <dev/wscons/wsconsio.h>
133 #include <dev/wscons/wsmousevar.h>
134 
135 
136 /*
137  * Debugging output.
138  */
139 
140 
141 /* XXX Should be redone, and its use should be added back. */
142 
143 #ifdef PBMS_DEBUG
144 
145 /*
146  * Print the error message (preceded by the driver and function)
147  * specified by the string literal fmt (followed by newline) if
148  * pbmsdebug is greater than n. The macro may only be used in the
149  * scope of sc, which must be castable to struct device *. There must
150  * be at least one vararg. Do not define PBMS_DEBUG on non-C99
151  * compilers.
152  */
153 
154 #define DPRINTFN(n, fmt, ...)						      \
155 do {									      \
156 	if (pbmsdebug > (n))						      \
157 		logprintf("%s: %s: " fmt "\n",				      \
158 			  ((struct device *) sc)->dv_xname,		      \
159 			  __func__, __VA_ARGS__);			      \
160 } while ( /* CONSTCOND */ 0)
161 
162 int pbmsdebug = 0;
163 
164 #endif /* PBMS_DEBUG */
165 
166 
167 /*
168  * Magic numbers.
169  */
170 
171 
172 /* The amount of data transfered by the USB device. */
173 #define PBMS_DATA_LEN 81
174 
175 /* The maximum number of sensors. */
176 #define PBMS_X_SENSORS 26
177 #define PBMS_Y_SENSORS 16
178 #define PBMS_SENSORS (PBMS_X_SENSORS + PBMS_Y_SENSORS)
179 
180 /*
181  * Parameters for supported devices.  For generality, these parameters
182  * can be different for each device.  The meanings of the parameters
183  * are as follows.
184  *
185  * desc:      A printable description used for dmesg output.
186  *
187  * noise:     Amount of noise in the computed position. This controls
188  *            how large a change must be to get reported, and how
189  *            large enough changes are smoothed.  A good value can
190  *            probably only be found experimentally, but something around
191  *            16 seems suitable.
192  *
193  * product:   The product ID of the trackpad.
194  *
195  *
196  * threshold: Accumulated changes less than this are ignored.  A good
197  *            value could be determined experimentally, but 5 is a
198  *            reasonable guess.
199  *
200  * vendor:    The vendor ID.  Currently USB_VENDOR_APPLE for all devices.
201  *
202  * x_factor:  Factor used in computations with X-coordinates.  If the
203  *            x-resolution of the display is x, this should be
204  *            (x + 1) / (x_sensors - 1).  Other values work fine, but
205  *            then the aspect ratio is not necessarily kept.
206  *
207  * x_sensors: The number of sensors in the X-direction.
208  *
209  * y_factor:  As x_factors, but for Y-coordinates.
210  *
211  * y_sensors: The number of sensors in the Y-direction.
212  */
213 
214 struct pbms_dev {
215 	const char *descr; /* Description of the driver (for dmesg). */
216 	int noise;	   /* Amount of noise in the computed position. */
217 	int threshold;	   /* Changes less than this are ignored. */
218 	int x_factor;	   /* Factor used in computation with X-coordinates. */
219 	int x_sensors;	   /* The number of X-sensors. */
220 	int y_factor;	   /* Factor used in computation with Y-coordinates. */
221 	int y_sensors;	   /* The number of Y-sensors. */
222 	uint16_t product;  /* Product ID. */
223 	uint16_t vendor;   /* The vendor ID. */
224 };
225 
226 /* Devices supported by this driver. */
227 static struct pbms_dev pbms_devices[] =
228 {
229 #define POWERBOOK_TOUCHPAD(inches, prod, x_fact, x_sens, y_fact)	      \
230        {								      \
231 		.descr = #inches " inch PowerBook Trackpad",		      \
232 		.vendor = USB_VENDOR_APPLE,				      \
233 		.product = (prod),					      \
234 		.noise = 16,						      \
235 		.threshold = 5,						      \
236 		.x_factor = (x_fact),					      \
237 		.x_sensors = (x_sens),					      \
238 		.y_factor = (y_fact),					      \
239 		.y_sensors = 16						      \
240        }
241        /* 12 inch PowerBooks */
242        POWERBOOK_TOUCHPAD(12, 0x030a, 69, 16, 52), /* XXX Not tested. */
243        /* 15 inch PowerBooks */
244        POWERBOOK_TOUCHPAD(15, 0x020e, 85, 16, 57), /* XXX Not tested. */
245        POWERBOOK_TOUCHPAD(15, 0x020f, 85, 16, 57),
246        POWERBOOK_TOUCHPAD(15, 0x0215, 64, 16, 43),
247        /* 17 inch PowerBooks */
248        POWERBOOK_TOUCHPAD(17, 0x020d, 71, 26, 68)  /* XXX Not tested. */
249 #undef POWERBOOK_TOUCHPAD
250 };
251 
252 /* The number of supported devices. */
253 #define PBMS_NUM_DEVICES (sizeof(pbms_devices) / sizeof(pbms_devices[0]))
254 
255 
256 /*
257  * Types and prototypes.
258  */
259 
260 
261 /* Device data. */
262 struct pbms_softc {
263 	struct uhidev sc_hdev;	      /* USB parent (got the struct device). */
264 	int is_geyser2;
265 	int sc_datalen;
266 	int sc_acc[PBMS_SENSORS];     /* Accumulated sensor values. */
267 	unsigned char sc_prev[PBMS_SENSORS];   /* Previous sample. */
268 	unsigned char sc_sample[PBMS_SENSORS]; /* Current sample. */
269 	struct device *sc_wsmousedev; /* WSMouse device. */
270 	int sc_noise;		      /* Amount of noise. */
271 	int sc_theshold;	      /* Threshold value. */
272 	int sc_x;		      /* Virtual position in horizontal
273 				       * direction (wsmouse position). */
274 	int sc_x_factor;	      /* X-coordinate factor. */
275 	int sc_x_raw;		      /* X-position of finger on trackpad. */
276 	int sc_x_sensors;	      /* Number of X-sensors. */
277 	int sc_y;		      /* Virtual position in vertical direction
278 				       * (wsmouse position). */
279 	int sc_y_factor;	      /* Y-coordinate factor. */
280 	int sc_y_raw;		      /* Y-position of finger on trackpad. */
281 	int sc_y_sensors;	      /* Number of Y-sensors. */
282 	uint32_t sc_buttons;	      /* Button state. */
283 	uint32_t sc_status;	      /* Status flags. */
284 #define PBMS_ENABLED 1		      /* Is the device enabled? */
285 #define PBMS_DYING 2		      /* Is the device dying? */
286 #define PBMS_VALID 4		      /* Is the previous sample valid? */
287 };
288 
289 
290 /* Static function prototypes. */
291 static void pbms_intr(struct uhidev *, void *, unsigned int);
292 static int pbms_enable(void *);
293 static void pbms_disable(void *);
294 static int pbms_ioctl(void *, unsigned long, void *, int, struct lwp *);
295 static void reorder_sample(struct pbms_softc *, unsigned char *, unsigned char *);
296 static int compute_delta(struct pbms_softc *, int *, int *, int *, uint32_t *);
297 static int detect_pos(int *, int, int, int, int *, int *);
298 static int smooth_pos(int, int, int);
299 
300 /* Access methods for wsmouse. */
301 const struct wsmouse_accessops pbms_accessops = {
302 	pbms_enable,
303 	pbms_ioctl,
304 	pbms_disable,
305 };
306 
307 /* This take cares also of the basic device registration. */
308 USB_DECLARE_DRIVER(pbms);
309 
310 
311 /*
312  * Basic driver.
313  */
314 
315 
316 /* Try to match the device at some uhidev. */
317 
318 int
319 pbms_match(struct device *parent, struct cfdata *match, void *aux)
320 {
321 	struct uhidev_attach_arg *uha = aux;
322 	usb_device_descriptor_t *udd;
323 	int i;
324 	uint16_t vendor, product;
325 
326 	/*
327 	 * We just check if the vendor and product IDs have the magic numbers
328 	 * we expect.
329 	 */
330 	if ((udd = usbd_get_device_descriptor(uha->parent->sc_udev)) != NULL) {
331 		vendor = UGETW(udd->idVendor);
332 		product = UGETW(udd->idProduct);
333 		for (i = 0; i < PBMS_NUM_DEVICES; i++) {
334 			if (vendor == pbms_devices[i].vendor &&
335 			    product == pbms_devices[i].product)
336 				return UMATCH_IFACECLASS;
337 		}
338 	}
339 	return UMATCH_NONE;
340 }
341 
342 
343 /* Attach the device. */
344 
345 void
346 pbms_attach(struct device *parent, struct device *self, void *aux)
347 {
348 	struct wsmousedev_attach_args a;
349 	struct uhidev_attach_arg *uha = aux;
350 	struct pbms_dev *pd;
351 	struct pbms_softc *sc = (struct pbms_softc *)self;
352 	usb_device_descriptor_t *udd;
353 	int i;
354 	uint16_t vendor, product;
355 
356 	sc->sc_hdev.sc_intr = pbms_intr;
357 	sc->sc_hdev.sc_parent = uha->parent;
358 	sc->sc_hdev.sc_report_id = uha->reportid;
359 
360 	sc->is_geyser2 = 0;
361 	sc->sc_datalen = PBMS_DATA_LEN;
362 
363 	/* Fill in device-specific parameters. */
364 	if ((udd = usbd_get_device_descriptor(uha->parent->sc_udev)) != NULL) {
365 		product = UGETW(udd->idProduct);
366 		vendor = UGETW(udd->idVendor);
367 		for (i = 0; i < PBMS_NUM_DEVICES; i++) {
368 			pd = &pbms_devices[i];
369 			if (product == pd->product && vendor == pd->vendor) {
370 				printf(": %s\n", pd->descr);
371 				sc->sc_noise = pd->noise;
372 				sc->sc_theshold = pd->threshold;
373 				sc->sc_x_factor = pd->x_factor;
374 				sc->sc_x_sensors = pd->x_sensors;
375 				sc->sc_y_factor = pd->y_factor;
376 				sc->sc_y_sensors = pd->y_sensors;
377 				if (product == 0x215) {
378 					sc->is_geyser2 = 1;
379 					sc->sc_x_sensors = 15;
380 					sc->sc_y_sensors = 9;
381 					sc->sc_datalen = 64;
382 				}
383 				break;
384 			}
385 		}
386 	}
387 	KASSERT(0 <= sc->sc_x_sensors && sc->sc_x_sensors <= PBMS_X_SENSORS);
388 	KASSERT(0 <= sc->sc_y_sensors && sc->sc_y_sensors <= PBMS_Y_SENSORS);
389 
390 	sc->sc_status = 0;
391 
392 	a.accessops = &pbms_accessops;
393 	a.accesscookie = sc;
394 
395 	sc->sc_wsmousedev = config_found(self, &a, wsmousedevprint);
396 
397 	USB_ATTACH_SUCCESS_RETURN;
398 }
399 
400 
401 /* Detach the device. */
402 
403 int
404 pbms_detach(struct device *self, int flags)
405 {
406 	struct pbms_softc *sc = (struct pbms_softc *)self;
407 	int ret;
408 
409 	/* The wsmouse driver does all the work. */
410 	ret = 0;
411 	if (sc->sc_wsmousedev != NULL)
412 		ret = config_detach(sc->sc_wsmousedev, flags);
413 
414 	return ret;
415 }
416 
417 
418 /* Activate the device. */
419 
420 int
421 pbms_activate(device_ptr_t self, enum devact act)
422 {
423 	struct pbms_softc *sc = (struct pbms_softc *)self;
424 	int ret;
425 
426 	if (act == DVACT_DEACTIVATE) {
427 		ret = 0;
428 		if (sc->sc_wsmousedev != NULL)
429 			ret = config_deactivate(sc->sc_wsmousedev);
430 		sc->sc_status |= PBMS_DYING;
431 		return ret;
432 	}
433 	return EOPNOTSUPP;
434 }
435 
436 
437 /* Enable the device. */
438 
439 static int
440 pbms_enable(void *v)
441 {
442 	struct pbms_softc *sc = v;
443 
444 	/* Check that we are not detaching or already enabled. */
445 	if (sc->sc_status & PBMS_DYING)
446 		return EIO;
447 	if (sc->sc_status & PBMS_ENABLED)
448 		return EBUSY;
449 
450 	sc->sc_status |= PBMS_ENABLED;
451 	sc->sc_status &= ~PBMS_VALID;
452 	sc->sc_buttons = 0;
453 	memset(sc->sc_sample, 0, sizeof(sc->sc_sample));
454 
455 	return uhidev_open(&sc->sc_hdev);
456 }
457 
458 
459 /* Disable the device. */
460 
461 static void
462 pbms_disable(void *v)
463 {
464 	struct pbms_softc *sc = v;
465 
466 	if (!(sc->sc_status & PBMS_ENABLED))
467 		return;
468 
469 	sc->sc_status &= ~PBMS_ENABLED;
470 	uhidev_close(&sc->sc_hdev);
471 }
472 
473 
474 /* XXX ioctl not implemented. */
475 
476 static int
477 pbms_ioctl(void *v, unsigned long cmd, void *data, int flag, struct lwp *p)
478 {
479 	return EPASSTHROUGH;
480 }
481 
482 
483 /*
484  * Interrupts & pointer movement.
485  */
486 
487 
488 /* Handle interrupts. */
489 
490 void
491 pbms_intr(struct uhidev *addr, void *ibuf, unsigned int len)
492 {
493 	struct pbms_softc *sc = (struct pbms_softc *)addr;
494 	unsigned char *data;
495 	int dx, dy, dz, i, s;
496 	uint32_t buttons;
497 
498 	/* Ignore incomplete data packets. */
499 	if (len != sc->sc_datalen)
500 		return;
501 	data = ibuf;
502 
503 #if 0
504 	printf("(");
505 	for (i = 0; i < len; i++)
506 		printf(" %d", data[i]);
507 	printf(" )\n");
508 #endif
509 
510 	/* The last byte is 1 if the button is pressed and 0 otherwise. */
511 	buttons = !!data[sc->sc_datalen - 1];
512 
513 	/* Everything below assumes that the sample is reordered. */
514 	reorder_sample(sc, sc->sc_sample, data);
515 
516 	/* Is this the first sample? */
517 	if (!(sc->sc_status & PBMS_VALID)) {
518 		sc->sc_status |= PBMS_VALID;
519 		sc->sc_x = sc->sc_y = -1;
520 		sc->sc_x_raw = sc->sc_y_raw = -1;
521 		memcpy(sc->sc_prev, sc->sc_sample, sizeof(sc->sc_prev));
522 		memset(sc->sc_acc, 0, sizeof(sc->sc_acc));
523 		return;
524 	}
525 	/* Accumulate the sensor change while keeping it nonnegative. */
526 	for (i = 0; i < PBMS_SENSORS; i++) {
527 		sc->sc_acc[i] +=
528 			(signed char) (sc->sc_sample[i] - sc->sc_prev[i]);
529 		if (sc->sc_acc[i] < 0)
530 			sc->sc_acc[i] = 0;
531 	}
532 	memcpy(sc->sc_prev, sc->sc_sample, sizeof(sc->sc_prev));
533 
534 	/* Compute change. */
535 	dx = dy = dz = 0;
536 	if (!compute_delta(sc, &dx, &dy, &dz, &buttons))
537 		return;
538 
539 	/* Report to wsmouse. */
540 	if ((dx != 0 || dy != 0 || dz != 0 || buttons != sc->sc_buttons) &&
541 	    sc->sc_wsmousedev != NULL) {
542 		s = spltty();
543 		wsmouse_input(sc->sc_wsmousedev, buttons, dx, -dy, dz, 0,
544 		    WSMOUSE_INPUT_DELTA);
545 		splx(s);
546 	}
547 	sc->sc_buttons = buttons;
548 }
549 
550 
551 /*
552  * Reorder the sensor values so that all the X-sensors are before the
553  * Y-sensors in the natural order. Note that this might have to be
554  * rewritten if PBMS_X_SENSORS or PBMS_Y_SENSORS change.
555  */
556 
557 static void
558 reorder_sample(struct pbms_softc *sc, unsigned char *to, unsigned char *from)
559 {
560 	int i;
561 
562 	if (sc->is_geyser2) {
563 		int j;
564 
565 		memset(to, 0, PBMS_SENSORS);
566 		for (i = 0, j = 19; i < 20; i += 2, j += 3) {
567 			to[i] = from[j];
568 			to[i + 1] = from[j + 1];
569 		}
570 		for (i = 0, j = 1; i < 9; i += 2, j += 3) {
571 			to[PBMS_X_SENSORS + i] = from[j];
572 			to[PBMS_X_SENSORS + i + 1] = from[j + 1];
573 		}
574 	} else {
575 		for (i = 0; i < 8; i++) {
576 			/* X-sensors. */
577 			to[i] = from[5 * i + 2];
578 			to[i + 8] = from[5 * i + 4];
579 			to[i + 16] = from[5 * i + 42];
580 	#if 0
581 			/*
582 			 * XXX This seems to introduce random ventical jumps, so
583 			 * we ignore these sensors until we figure out their meaning.
584 			 */
585 			if (i < 2)
586 				to[i + 24] = from[5 * i + 44];
587 	#endif /* 0 */
588 			/* Y-sensors. */
589 			to[i + 26] = from[5 * i + 1];
590 			to[i + 34] = from[5 * i + 3];
591 		}
592 	}
593 }
594 
595 
596 /*
597  * Compute the change in x, y and z direction, update the button state
598  * (to simulate more than one button, scrolling etc.), and update the
599  * history. Note that dx, dy, dz and buttons are modified only if
600  * corresponding pressure is detected and should thus be initialised
601  * before the call.  Return 0 on error.
602  */
603 
604 /* XXX Could we report something useful in dz? */
605 
606 static int
607 compute_delta(struct pbms_softc *sc, int *dx, int *dy, int *dz,
608 	      uint32_t * buttons)
609 {
610 	int x_det, y_det, x_raw, y_raw, x_fingers, y_fingers, fingers, x, y;
611 
612 	x_det = detect_pos(sc->sc_acc, sc->sc_x_sensors, sc->sc_theshold,
613 			   sc->sc_x_factor, &x_raw, &x_fingers);
614 	y_det = detect_pos(sc->sc_acc + PBMS_X_SENSORS, sc->sc_y_sensors,
615 			   sc->sc_theshold, sc->sc_y_factor,
616 			   &y_raw, &y_fingers);
617 	fingers = max(x_fingers, y_fingers);
618 
619 	/* Check the number of fingers and if we have detected a position. */
620 	if (fingers > 1) {
621 		/* More than one finger detected, resetting. */
622 		memset(sc->sc_acc, 0, sizeof(sc->sc_acc));
623 		sc->sc_x_raw = sc->sc_y_raw = sc->sc_x = sc->sc_y = -1;
624 		return 0;
625 	} else if (x_det == 0 && y_det == 0) {
626 		/* No position detected, resetting. */
627 		memset(sc->sc_acc, 0, sizeof(sc->sc_acc));
628 		sc->sc_x_raw = sc->sc_y_raw = sc->sc_x = sc->sc_y = -1;
629 	} else if (x_det > 0 && y_det > 0) {
630 		/* Smooth position. */
631 		if (sc->sc_x_raw >= 0) {
632 			sc->sc_x_raw = (3 * sc->sc_x_raw + x_raw) / 4;
633 			sc->sc_y_raw = (3 * sc->sc_y_raw + y_raw) / 4;
634 			/*
635 			 * Compute virtual position and change if we already
636 			 * have a decent position.
637 			 */
638 			if (sc->sc_x >= 0) {
639 				x = smooth_pos(sc->sc_x, sc->sc_x_raw,
640 					       sc->sc_noise);
641 				y = smooth_pos(sc->sc_y, sc->sc_y_raw,
642 					       sc->sc_noise);
643 				*dx = x - sc->sc_x;
644 				*dy = y - sc->sc_y;
645 				sc->sc_x = x;
646 				sc->sc_y = y;
647 			} else {
648 				/* Initialise virtual position. */
649 				sc->sc_x = sc->sc_x_raw;
650 				sc->sc_y = sc->sc_y_raw;
651 			}
652 		} else {
653 			/* Initialise raw position. */
654 			sc->sc_x_raw = x_raw;
655 			sc->sc_y_raw = y_raw;
656 		}
657 	}
658 	return 1;
659 }
660 
661 
662 /*
663  * Compute the new smoothed position from the previous smoothed position
664  * and the raw position.
665  */
666 
667 static int
668 smooth_pos(int pos_old, int pos_raw, int noise)
669 {
670 	int ad, delta;
671 
672 	delta = pos_raw - pos_old;
673 	ad = abs(delta);
674 
675 	/* Too small changes are ignored. */
676 	if (ad < noise / 2)
677 		delta = 0;
678 	/* A bit larger changes are smoothed. */
679 	else if (ad < noise)
680 		delta /= 4;
681 	else if (ad < 2 * noise)
682 		delta /= 2;
683 
684 	return pos_old + delta;
685 }
686 
687 
688 /*
689  * Detect the position of the finger.  Returns the total pressure.
690  * The position is returned in pos_ret and the number of fingers
691  * is returned in fingers_ret.  The position returned in pos_ret
692  * is in [0, (n_sensors - 1) * factor - 1].
693  */
694 
695 static int
696 detect_pos(int *sensors, int n_sensors, int threshold, int fact,
697 	   int *pos_ret, int *fingers_ret)
698 {
699 	int i, w, s;
700 
701 	/*
702 	 * Compute the number of fingers, total pressure, and weighted
703 	 * position of the fingers.
704 	 */
705 	*fingers_ret = 0;
706 	w = s = 0;
707 	for (i = 0; i < n_sensors; i++) {
708 		if (sensors[i] >= threshold) {
709 			if (i == 0 || sensors[i - 1] < threshold)
710 				*fingers_ret += 1;
711 			s += sensors[i];
712 			w += sensors[i] * i;
713 		}
714 	}
715 
716 	if (s > 0)
717 		*pos_ret = w * fact / s;
718 
719 	return s;
720 }
721