1/* sane - Scanner Access Now Easy.
2
3   Copyright (C) 2001-2003 Eddy De Greef <eddy_de_greef at scarlet dot be>
4   This file is part of the SANE package.
5
6   This program is free software; you can redistribute it and/or
7   modify it under the terms of the GNU General Public License as
8   published by the Free Software Foundation; either version 2 of the
9   License, or (at your option) any later version.
10
11   This program is distributed in the hope that it will be useful, but
12   WITHOUT ANY WARRANTY; without even the implied warranty of
13   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14   General Public License for more details.
15
16   You should have received a copy of the GNU General Public License
17   along with this program.  If not, see <https://www.gnu.org/licenses/>.
18
19   As a special exception, the authors of SANE give permission for
20   additional uses of the libraries contained in this release of SANE.
21
22   The exception is that, if you link a SANE library with other files
23   to produce an executable, this does not by itself cause the
24   resulting executable to be covered by the GNU General Public
25   License.  Your use of that executable is in no way restricted on
26   account of linking the SANE library code into it.
27
28   This exception does not, however, invalidate any other reasons why
29   the executable file might be covered by the GNU General Public
30   License.
31
32   If you submit changes to SANE to the maintainers to be included in
33   a subsequent release, you agree by submitting the changes that
34   those changes may be distributed with this exception intact.
35
36   If you write modifications of your own for SANE, it is your choice
37   whether to permit this exception to apply to your modifications.
38   If you do not wish that, delete this exception notice.
39
40   This file implements a SANE backend for Mustek PP flatbed _CIS_ scanners.
41*/
42
43/*
44   Global picture
45
46      Mustek_PP_handle -> Mustek_PP_dev
47                       -> priv = Mustek_PP_CIS_dev -> CIS
48*/
49
50/*
51 * This flag determines whether the scanner uses fast skipping at high
52 * resolutions. It is possible that this fast skipping introduces
53 * inaccuracies. It if turns out to be a problem, fast skipping can
54 * be disabled by setting this flag to 0.
55 */
56#define MUSTEK_PP_CIS_FAST_SKIP 1
57#define MUSTEK_PP_CIS_WAIT_BANK 200
58
59/*
60 * These parameters determine where the scanable area starts at the top.
61 * If there is a consistent offset error, you can tune it through these
62 * parameters. Note that an inaccuracy in the order of 1 mm seems to be
63 * normal for the Mustek 600/1200 CP series.
64 */
65#define MUSTEK_PP_CIS_600CP_DEFAULT_SKIP   	250
66#define MUSTEK_PP_CIS_1200CP_DEFAULT_SKIP 	330
67
68/*
69 * Number of scan lines on which the average is taken to determine the
70 * maximum number of color levels.
71 */
72#define MUSTEK_PP_CIS_AVERAGE_COUNT 32
73
74#define MUSTEK_PP_CIS600		1
75#define MUSTEK_PP_CIS1200		2
76#define MUSTEK_PP_CIS1200PLUS 		3
77
78#define MUSTEK_PP_CIS_CHANNEL_RED	0
79#define MUSTEK_PP_CIS_CHANNEL_GREEN	1
80#define MUSTEK_PP_CIS_CHANNEL_BLUE	2
81#define MUSTEK_PP_CIS_CHANNEL_GRAY	1
82
83#define MUSTEK_PP_CIS_MAX_H_PIXEL 	5118
84#define MUSTEK_PP_CIS_MAX_V_PIXEL 	7000
85
86#define MUSTEK_PP_CIS_MOTOR_REVERSE 	0
87
88#include "../include/sane/config.h"
89
90#include <assert.h>
91#include <string.h>
92#include <stdlib.h>
93#include <stdio.h>
94#include <unistd.h>
95#include <math.h>
96#ifdef HAVE_SYS_SELECT_H
97# include <sys/select.h>
98#endif
99#include "../include/sane/sane.h"
100#include "../include/sane/sanei_pa4s2.h"
101#define DEBUG_DECLARE_ONLY
102#include "mustek_pp.h"
103#include "mustek_pp_decl.h"
104#include "mustek_pp_cis.h"
105
106/******************************************************************************
107 ******************************************************************************
108 ***                 MA1015 chipset related functionality                   ***
109 ******************************************************************************
110 *****************************************************************************/
111
112/*
113   These defines control some debugging functionality
114
115   #define M1015_TRACE_REGS   -> trace the status of the internal registers
116   #define M1015_LOG_HL       -> create a high-level log file (register-level)
117   #define M1015_LOG_LL       -> create a low-level log file (byte-level)
118
119   By default, all logging/tracing is turned off.
120*/
121
122/******************************************************************************
123 * Low level logging: logs read and writes at the byte level, similar to
124 *                    the sequences produced by tool of Jochen Eisinger
125 *                    for analysing the TWAIN driver communication.
126 *                    This simplifies comparison of the sequences.
127 *****************************************************************************/
128#ifdef M1015_LOG_LL
129
130   static FILE* M1015_LOG_1;
131
132   #define M1015_START_LL\
133      M1015_LOG_1 = fopen("cis_ll.log", "w");
134
135   #define M1015_STOP_LL\
136      fclose(M1015_LOG_1);
137
138   #define SANEI_PA4S2_WRITEBYTE(fd, reg, val)\
139      do\
140      {\
141         sanei_pa4s2_writebyte (fd, reg, val);\
142         fprintf(M1015_LOG_1, "\tsanei_pa4s2_writebyte(fd, %d, 0x%02X);\n", \
143                 reg, val);\
144      } while (0)
145
146   static const char* cis_last_rreg_name;
147   static int cis_read_count;
148
149   #define SANEI_PA4S2_READBEGIN(fd, reg)\
150      do\
151      {\
152         cis_last_rreg_name = Mustek_PP_1015_reg_r_name(reg);\
153         cis_read_count = 0;\
154         sanei_pa4s2_readbegin(fd, reg);\
155      } while (0)
156
157   #define SANEI_PA4S2_READBYTE(fd, val)\
158      do\
159      {\
160         sanei_pa4s2_readbyte(fd, val);\
161         ++cis_read_count;\
162      } while (0)
163
164   #define SANEI_PA4S2_READEND(fd)\
165      do\
166      {\
167         sanei_pa4s2_readend(fd);\
168         fprintf(M1015_LOG_1, "\tread_reg(%s, %d);\n", \
169                 cis_last_rreg_name, cis_read_count);\
170      } while (0)
171
172   #define M1015_MARK_LL(info)\
173      fprintf(M1015_LOG_1, "* %s\n", info);
174
175#else /* M1015_LOG_LL */
176
177   #define M1015_START_LL
178   #define M1015_STOP_LL
179
180   #define SANEI_PA4S2_WRITEBYTE(fd, reg, val)\
181      sanei_pa4s2_writebyte (fd, reg, val)
182
183   #define SANEI_PA4S2_READBEGIN(fd, reg)\
184      sanei_pa4s2_readbegin(fd, reg)
185
186   #define SANEI_PA4S2_READBYTE(fd, val)\
187      sanei_pa4s2_readbyte(fd, val)
188
189   #define SANEI_PA4S2_READEND(fd)\
190      sanei_pa4s2_readend(fd)
191
192   #define M1015_MARK_LL(info)
193
194#endif /* M1015_LOG_LL */
195
196
197/******************************************************************************
198 * High-level logging: traces the flow of the driver in a hierarchical way
199 *                     up to the level of register accesses.
200 *****************************************************************************/
201#ifdef M1015_LOG_HL
202
203   static FILE* M1015_LOG_2;
204   static char hl_prev_line[4096], hl_next_line[4096], hl_repeat_count;
205
206   /*
207    * A few variables for hierarchical log message indentation.
208    */
209
210   static const char* cis_indent_start =
211      "                                                                      ";
212   static const char* cis_indent;
213   static const char* cis_indent_end;
214
215   #define M1015_START_HL\
216       M1015_LOG_2 = fopen("cis_hl.log", "w");\
217       cis_indent = cis_indent_start + strlen(cis_indent_start);\
218       cis_indent_end = cis_indent;\
219       hl_prev_line[0] = 0;\
220       hl_next_line[0] = 0;\
221       hl_repeat_count = 0;
222
223   #define M1015_FLUSH_HL\
224      if (strcmp(hl_prev_line, hl_next_line))\
225      {\
226         fprintf(M1015_LOG_2, &hl_prev_line[0]);\
227         strcpy(&hl_prev_line[0], &hl_next_line[0]);\
228         if (hl_repeat_count != 0)\
229         {\
230            fprintf(M1015_LOG_2, "%s [last message repeated %d times]\n",\
231                    cis_indent, hl_repeat_count+1);  \
232         }\
233         hl_repeat_count = 0;\
234      }\
235      else\
236      {\
237         hl_repeat_count += 1;\
238      }
239
240   #define M1015_MARK(info)\
241      sprintf(&hl_next_line[0], "%s+ %s\n", cis_indent, info);\
242      M1015_FLUSH_HL
243
244   #define M1015_STOP_HL\
245       hl_next_line[0] = 0;\
246       M1015_FLUSH_HL\
247       fclose(M1015_LOG_2);
248
249#else  /* M1015_LOG_HL */
250
251   #define M1015_START_HL
252   #define M1015_STOP_HL
253   #define M1015_MARK(info)
254   #define M1015_FLUSH_HL
255
256#endif /* M1015_LOG_HL */
257
258#ifdef M1015_TRACE_REGS
259   #define M1015_DISPLAY_REGS(dev, msg) Mustek_PP_1015_display_regs(dev, msg)
260   #define M1015_DISPLAY_REG(msg, val)  Mustek_PP_1015_display_reg(msg, val)
261#else
262   #define M1015_DISPLAY_REGS(dev, msg)
263   #define M1015_DISPLAY_REG(msg, val)
264#endif
265
266
267#if defined (M1015_LOG_HL) || defined (M1015_LOG_LL)
268static const char*
269Mustek_PP_1015_reg_r_name(Mustek_PP_1015R_reg id)
270{
271   static const char* names[4] = { "ASIC", "SCAN_VAL", "MOTOR", "BANK_COUNT" };
272   return names[id & 0x03];
273}
274
275static const char*
276Mustek_PP_1015_bit_name(Mustek_PP_1015R_bit id)
277{
278   static const char* names[4] = { "????", "MOTOR_HOME", "????", "MOTOR_BUSY" };
279   return names[id & 0x03];
280}
281
282static const char*
283Mustek_PP_1015_reg_w_name(Mustek_PP_1015R_reg id)
284{
285   static const char* names[4][4] =
286   {
287      { "RED_REF",        "GREEN_REF",     "BLUE_REF",       "DPI_CONTROL" },
288      { "BYTE_COUNT_HB",  "BYTE_COUNT_LB", "SKIP_COUNT",     "EXPOSE_TIME" },
289      { "SRAM_SOURCE_PC", "MOTOR_CONTROL", "UNKNOWN_42",     "UNKNOWN_82"  },
290      { "POWER_ON_DELAY", "CCD_TIMING",    "CCD_TIMING_ADJ", "RIGHT_BOUND" }
291   };
292   return names[(id & 0x30) >> 4][id & 0x03];
293}
294#endif
295
296/******************************************************************************
297 * Converts a register value to a hex/dec/bin representation.
298 *****************************************************************************/
299static const char*
300Mustek_PP_1015_show_val(int val)
301{
302   /*
303      Since we use a static temporary buffer, we must make sure that the
304      buffer isn't altered while it is still in use (typically because
305      more than one value is converted in a printf statement).
306      Therefore the buffer is organized as a ring buffer. If should contain
307      at least 21 elements in order to be able to display all registers
308      with one printf statement.
309   */
310   #define Mustek_PP_1015_RING_BUFFER_SIZE 50
311   static char buf[Mustek_PP_1015_RING_BUFFER_SIZE][64];
312   static int index = 0;
313   int i;
314   char* current = (char*)buf[index++];
315
316   if (index >= Mustek_PP_1015_RING_BUFFER_SIZE) index = 0;
317
318   if (val < 0)
319   {
320      /* The register has not been initialized yet. */
321      sprintf(current, "---- (---) --------");
322   }
323   else
324   {
325      sprintf(current, "0x%02X (%3d) ", val & 0xFF, val & 0xFF);
326      for (i=0; i<8; ++i)
327      {
328         sprintf(current+11+i, "%d", (val >> (7-i)) & 1);
329      }
330   }
331   return current;
332}
333
334#ifdef M1015_TRACE_REGS
335/******************************************************************************
336 * Displays the contents of all registers of the scanner on stderr.
337 *****************************************************************************/
338static void
339Mustek_PP_1015_display_regs(Mustek_PP_CIS_dev * dev, const char* info)
340{
341   /*
342    * Register naming convention:
343    *   Rx   : read-only register no. x
344    *   ByWx : write-only register no. x of bank no. y
345    */
346
347   fprintf(stderr,
348           "\n"
349           "Register status: %s\n"
350           "\n"
351           "    R0: %s  : ASIC info\n"
352           "    R1: %s  : scan value\n"
353           "    R2: %s  : CCD/motor info\n"
354           "    R3: %s  : bank count\n"
355           "\n"
356           "  B0W0: %s  : red reference\n"
357           "  B0W1: %s  : green reference\n"
358           "  B0W2: %s  : blue reference\n"
359           "  B0W3: %s  : DPI control\n"
360           "\n"
361           "  B1W0: %s  : byte count, high byte\n"
362           "  B1W1: %s  : byte count, low byte\n"
363           "  B1W2: %s  : skip x32 pixels\n"
364           "  B1W3: %s  : expose time (CCDWIDTH)\n"
365           "\n"
366           "  B2W0: %s  : SRAM source PC\n"
367           "  B2W1: %s  : motor control\n"
368           "  B2W2: %s  : -\n"
369           "  B2W3: %s  : -\n"
370           "\n"
371           "  B3W0: %s  : power on delay\n"
372           "  B3W1: %s  : CCD timing - always 0x05\n"
373           "  B3W2: %s  : CCD timing adjust - always 0x00\n"
374           "  B3W3: %s  : right bound (not used)\n"
375           "\n"
376           "  CHAN: %s  : channel [%s]\n"
377           "\n",
378           info,
379           Mustek_PP_1015_show_val (dev->CIS.regs.in_regs[0]),
380           Mustek_PP_1015_show_val (dev->CIS.regs.in_regs[1]),
381           Mustek_PP_1015_show_val (dev->CIS.regs.in_regs[2]),
382           Mustek_PP_1015_show_val (dev->CIS.regs.in_regs[3]),
383           Mustek_PP_1015_show_val (dev->CIS.regs.out_regs[0][0]),
384           Mustek_PP_1015_show_val (dev->CIS.regs.out_regs[0][1]),
385           Mustek_PP_1015_show_val (dev->CIS.regs.out_regs[0][2]),
386           Mustek_PP_1015_show_val (dev->CIS.regs.out_regs[0][3]),
387           Mustek_PP_1015_show_val (dev->CIS.regs.out_regs[1][0]),
388           Mustek_PP_1015_show_val (dev->CIS.regs.out_regs[1][1]),
389           Mustek_PP_1015_show_val (dev->CIS.regs.out_regs[1][2]),
390           Mustek_PP_1015_show_val (dev->CIS.regs.out_regs[1][3]),
391           Mustek_PP_1015_show_val (dev->CIS.regs.out_regs[2][0]),
392           Mustek_PP_1015_show_val (dev->CIS.regs.out_regs[2][1]),
393           Mustek_PP_1015_show_val (dev->CIS.regs.out_regs[2][2]),
394           Mustek_PP_1015_show_val (dev->CIS.regs.out_regs[2][3]),
395           Mustek_PP_1015_show_val (dev->CIS.regs.out_regs[3][0]),
396           Mustek_PP_1015_show_val (dev->CIS.regs.out_regs[3][1]),
397           Mustek_PP_1015_show_val (dev->CIS.regs.out_regs[3][2]),
398           Mustek_PP_1015_show_val (dev->CIS.regs.out_regs[3][3]),
399           Mustek_PP_1015_show_val (dev->CIS.regs.channel),
400           (dev->CIS.regs.channel == 0x80 ? "RED"   :
401           (dev->CIS.regs.channel == 0x40 ? "GREEN" :
402           (dev->CIS.regs.channel == 0xC0 ? "BLUE"  : "unknown")))
403           );
404}
405
406/******************************************************************************
407 * Displays a single register value
408 *****************************************************************************/
409static void
410Mustek_PP_1015_display_reg(const char* info, int val)
411{
412   fprintf (stderr, "%s: %s\n", info, Mustek_PP_1015_show_val(val));
413}
414
415#endif /* M1015_TRACE_REGS */
416
417
418/******************************************************************************
419 *
420 * Reads one of the 4 internal registers of the scanner
421 *
422 *   0: ASIC identification
423 *   1: scan values
424 *   2: CCD info / motor info
425 *   3: bank count info
426 *
427 *****************************************************************************/
428static SANE_Byte
429Mustek_PP_1015_read_reg(Mustek_PP_CIS_dev * dev, Mustek_PP_1015R_reg reg)
430{
431   SANE_Byte tmp;
432   assert(reg <= 3);
433
434   SANEI_PA4S2_READBEGIN (dev->desc->fd, reg & 0x03);
435   SANEI_PA4S2_READBYTE (dev->desc->fd, &tmp);
436   SANEI_PA4S2_READEND (dev->desc->fd);
437
438#ifdef M1015_LOG_HL
439   sprintf(&hl_next_line[0], "%s read_reg(%s); [%s]\n", cis_indent,
440           Mustek_PP_1015_reg_r_name(reg), Mustek_PP_1015_show_val(tmp));
441   M1015_FLUSH_HL;
442#endif
443
444#ifdef M1015_TRACE_REGS
445   dev->CIS.regs.in_regs[reg & 0x03] = tmp;
446#endif
447
448   return tmp;
449}
450
451/******************************************************************************
452 *
453 * Waits for a bit of register to become 1 or 0. The period of checking can be
454 * controlled through the sleep parameter (microseconds).
455 *
456 *****************************************************************************/
457static SANE_Bool
458Mustek_PP_1015_wait_bit(Mustek_PP_CIS_dev * dev, Mustek_PP_1015R_reg reg,
459                        Mustek_PP_1015R_bit bit, SANE_Bool on, unsigned period)
460{
461   SANE_Byte tmp;
462   SANE_Byte mask, val;
463   int tries = 0;
464
465   assert(reg <= 3);
466   assert(bit <= 3);
467
468   mask = 1 << bit;
469
470   /* We don't want to wait forever */
471   while (dev->desc->state != STATE_CANCELLED)
472   {
473#if defined (M1015_LOG_LL) || defined (M1015_LOG_HL)
474      ++tries;
475#endif
476
477      sanei_pa4s2_readbegin (dev->desc->fd, reg & 0x03);
478      sanei_pa4s2_readbyte (dev->desc->fd, &tmp);
479      sanei_pa4s2_readend (dev->desc->fd);
480
481#ifdef M1015_LOG_HL
482   sprintf(&hl_next_line[0], "%s wait_bit(%s, %s, %d): %s %s;\n", cis_indent,
483           Mustek_PP_1015_reg_r_name(reg), Mustek_PP_1015_bit_name(bit),
484           on?1:0, Mustek_PP_1015_show_val(mask), Mustek_PP_1015_show_val(tmp));
485   M1015_FLUSH_HL;
486#endif
487      val = ((on == SANE_TRUE) ? tmp : ~tmp ) & mask;
488
489      if (val != 0) break;
490
491      if (period) usleep(period);
492
493      if (tries > 50000)
494      {
495#ifdef M1015_LOG_HL
496         sprintf(&hl_next_line[0], "%s wait_bit(%s, %s, %d): failed;\n", cis_indent,
497           Mustek_PP_1015_reg_r_name(reg), Mustek_PP_1015_bit_name(bit), on?1:0);
498         M1015_FLUSH_HL;
499#endif
500         DBG(2, "Mustek_PP_1015_wait_bit: failed (reg %d, bit %d, on: %d)\n",
501             reg, bit, on?1:0);
502         return SANE_FALSE;
503      }
504   }
505
506#ifdef M1015_LOG_HL
507   sprintf(&hl_next_line[0], "%s wait_bit(%s, %s, %d);\n", cis_indent,
508           Mustek_PP_1015_reg_r_name(reg), Mustek_PP_1015_bit_name(bit), on?1:0);
509   M1015_FLUSH_HL;
510#endif
511#ifdef M1015_LOG_LL
512   fprintf(M1015_LOG_1, "\tread_reg(%s, %d);\n", Mustek_PP_1015_reg_r_name(reg),
513           tries);
514#endif
515
516#ifdef M1015_TRACE_REGS
517   dev->CIS.regs.in_regs[reg & 0x03] = tmp;
518#endif
519   return dev->desc->state != STATE_CANCELLED ? SANE_TRUE : SANE_FALSE;
520}
521
522/******************************************************************************
523 *
524 * Writes one out of 4 registers of one of the 4 register banks (I guess)
525 *
526 * Bank 0
527 *    0: voltage red   --+
528 *    1: voltage green   +-> always set to 0x96
529 *    2: voltage blue  --+
530 *    3: DPI control
531 *
532 * Bank 1
533 *    0: line adjust (?) - high byte
534 *    1: line adjust (?) - low  byte
535 *    2: unknown                       (values seen: 0x00, 0x02, 0x03, 0x1D)
536 *    3: expose time (?)               (values seen: 0xAA, 0xFD, 0xFE, 0xFF)
537 *
538 * Bank 2
539 *    0: unknown, used to start linear sequence during calibration
540 *    1: motor control code (forward, return home, ...)
541 *    2: never used
542 *    3: never used
543 *
544 * Bank 3
545 *    0: reduction factor (16bit internal -> 8bit) -> target for calibration
546 *    1: unknown -> always set to 0x05
547 *    2: unknown -> always set to 0x00
548 *    3: never used
549 *
550 *****************************************************************************/
551
552static void
553Mustek_PP_1015_write_reg(Mustek_PP_CIS_dev * dev, Mustek_PP_1015W_reg reg, SANE_Byte val)
554{
555
556   SANE_Byte regBank = (reg & 0xF0) >> 4;
557   SANE_Byte regNo   = (reg & 0x0F);
558
559   assert (regNo   <= 3);
560   assert (regBank <= 3);
561
562   SANEI_PA4S2_WRITEBYTE (dev->desc->fd, 6, (1 << (4+regNo))+ regBank);
563   SANEI_PA4S2_WRITEBYTE (dev->desc->fd, 5, val);
564   SANEI_PA4S2_WRITEBYTE (dev->desc->fd, 6, regBank);
565
566#ifdef M1015_TRACE_REGS
567   dev->CIS.regs.out_regs[regBank][regNo] = val;
568#endif
569
570#ifdef M1015_LOG_HL
571   sprintf(&hl_next_line[0], "%s write_reg(%s, 0x%02X);\n", cis_indent,
572           Mustek_PP_1015_reg_w_name(reg), val);
573   M1015_FLUSH_HL;
574#endif
575}
576
577/******************************************************************************
578 *
579 * Writes 2 values to 2 adjecent registers.
580 * It is probably equivalent to 2 simple write operations (but I'm not sure).
581 *
582 *   val1 is written to register[regNo]
583 *   val2 is written to register[regNo+1]
584 *
585 *****************************************************************************/
586static void
587Mustek_PP_1015_write_reg2(Mustek_PP_CIS_dev * dev, Mustek_PP_1015W_reg reg,
588               SANE_Byte val1, SANE_Byte val2)
589{
590   SANE_Byte regBank = (reg & 0xF0) >> 4;
591   SANE_Byte regNo   = (reg & 0x0F);
592
593   assert (regNo   <= 2);
594   assert (regBank <= 3);
595
596   SANEI_PA4S2_WRITEBYTE (dev->desc->fd, 6, (1 << (4+regNo))+ regBank);
597   SANEI_PA4S2_WRITEBYTE (dev->desc->fd, 5, val1);
598   SANEI_PA4S2_WRITEBYTE (dev->desc->fd, 6, (1 << (5+regNo))+ regBank);
599   SANEI_PA4S2_WRITEBYTE (dev->desc->fd, 5, val2);
600   SANEI_PA4S2_WRITEBYTE (dev->desc->fd, 6, regBank);
601
602#ifdef M1015_TRACE_REGS
603   dev->CIS.regs.out_regs[regBank][regNo]   = val1;
604   dev->CIS.regs.out_regs[regBank][regNo+1] = val2;
605#endif
606
607#ifdef M1015_LOG_HL
608   sprintf(&hl_next_line[0], "%s write_reg2(%s, 0x%02X, 0x%02X);\n",
609           cis_indent, Mustek_PP_1015_reg_w_name(reg), val1, val2);
610   M1015_FLUSH_HL;
611#endif
612}
613
614/******************************************************************************
615 *
616 * Writes 3 values to 3 adjecent registers.
617 * It is probably equivalent to 3 simple write operations (but I'm not sure).
618 *
619 *   val1 is written to register[regNo]
620 *   val2 is written to register[regNo+1]
621 *   val3 is written to register[regNo+2]
622 *
623 *****************************************************************************/
624static void
625Mustek_PP_1015_write_reg3(Mustek_PP_CIS_dev * dev, Mustek_PP_1015W_reg reg,
626               SANE_Byte val1, SANE_Byte val2, SANE_Byte val3)
627{
628   SANE_Byte regBank = (reg & 0xF0) >> 4;
629   SANE_Byte regNo   = (reg & 0x0F);
630
631   assert (regNo   <= 1);
632   assert (regBank <= 3);
633
634   SANEI_PA4S2_WRITEBYTE (dev->desc->fd, 6, (1 << (4+regNo))+ regBank);
635   SANEI_PA4S2_WRITEBYTE (dev->desc->fd, 5, val1);
636   SANEI_PA4S2_WRITEBYTE (dev->desc->fd, 6, (1 << (5+regNo))+ regBank);
637   SANEI_PA4S2_WRITEBYTE (dev->desc->fd, 5, val2);
638   SANEI_PA4S2_WRITEBYTE (dev->desc->fd, 6, (1 << (6+regNo))+ regBank);
639   SANEI_PA4S2_WRITEBYTE (dev->desc->fd, 5, val3);
640   SANEI_PA4S2_WRITEBYTE (dev->desc->fd, 6, regBank);
641
642#ifdef M1015_TRACE_REGS
643   dev->CIS.regs.out_regs[regBank][regNo  ] = val1;
644   dev->CIS.regs.out_regs[regBank][regNo+1] = val2;
645   dev->CIS.regs.out_regs[regBank][regNo+2] = val3;
646#endif
647
648#ifdef M1015_LOG_HL
649   sprintf(&hl_next_line[0], "%s write_reg3(%s, 0x%02X, 0x%02X, 0x%02X);\n",
650           cis_indent, Mustek_PP_1015_reg_w_name(reg), val1, val2, val3);
651   M1015_FLUSH_HL;
652#endif
653}
654
655/******************************************************************************
656 * Opens a register for a (series of) write operation(s).
657 *****************************************************************************/
658static void
659Mustek_PP_1015_write_reg_start(Mustek_PP_CIS_dev * dev, Mustek_PP_1015W_reg reg)
660{
661   SANE_Byte regBank = (reg & 0xF0) >> 4;
662   SANE_Byte regNo   = (reg & 0x0F);
663
664   assert (regNo   <= 3);
665   assert (regBank <= 3);
666
667   dev->CIS.regs.current_write_reg = reg;
668
669#ifdef M1015_LOG_HL
670   dev->CIS.regs.write_count = 0;
671#endif
672
673   SANEI_PA4S2_WRITEBYTE (dev->desc->fd, 6, (1 << (4+regNo))+ regBank);
674}
675
676/******************************************************************************
677 * Writes a value to the currently open register.
678 *****************************************************************************/
679static void
680Mustek_PP_1015_write_reg_val(Mustek_PP_CIS_dev * dev, SANE_Byte val)
681{
682#ifdef M1015_TRACE_REGS
683   SANE_Byte regBank = (dev->CIS.regs.current_write_reg & 0xF0) >> 4;
684   SANE_Byte regNo   = (dev->CIS.regs.current_write_reg & 0x0F);
685
686   assert (regNo   <= 3);
687   assert (regBank <= 3);
688
689   dev->CIS.regs.out_regs[regBank][regNo] = val;
690#endif
691
692   SANEI_PA4S2_WRITEBYTE (dev->desc->fd, 5, val);
693
694#ifdef M1015_LOG_HL
695   ++dev->CIS.regs.write_count;
696#endif
697}
698
699/******************************************************************************
700 * Closes a register after a (series of) write operation(s).
701 *****************************************************************************/
702static void
703Mustek_PP_1015_write_reg_stop(Mustek_PP_CIS_dev * dev)
704{
705   SANE_Byte regBank = (dev->CIS.regs.current_write_reg & 0xF0) >> 4;
706#ifdef M1015_LOG_HL
707   SANE_Byte regNo   = (dev->CIS.regs.current_write_reg & 0x0F);
708   assert (regNo   <= 3);
709
710   sprintf(&hl_next_line[0], "%s write_reg_multi(%s, *%d);\n",  cis_indent,
711           Mustek_PP_1015_reg_w_name(dev->CIS.regs.current_write_reg),
712           dev->CIS.regs.write_count);
713   M1015_FLUSH_HL;
714#endif
715   assert (regBank <= 3);
716
717   SANEI_PA4S2_WRITEBYTE (dev->desc->fd, 6, regBank);
718}
719
720/******************************************************************************
721 *
722 * Sends a command to the scanner. The command should not access one of the
723 * internal registers, ie., the 3rd bit should not be zero.
724 *
725 *****************************************************************************/
726static void
727Mustek_PP_1015_send_command(Mustek_PP_CIS_dev * dev, SANE_Byte command)
728{
729   assert (command & 0x04);
730   SANEI_PA4S2_WRITEBYTE (dev->desc->fd, 6, command);
731
732#ifdef M1015_LOG_HL
733   sprintf(&hl_next_line[0], "%s send_command(0x%02X);\n", cis_indent, command);
734   M1015_FLUSH_HL;
735#endif
736}
737
738/******************************************************************************
739 ##############################################################################
740 ##                              CIS driver                                  ##
741 ##############################################################################
742 *****************************************************************************/
743
744/******************************************************************************
745 * Resolution conversion functions
746 *****************************************************************************/
747static int
748max2hw_hres(Mustek_PP_CIS_dev *dev, int dist)
749{
750   return (int)((dist * dev->CIS.hw_hres) / dev->desc->dev->maxres + 0.5);
751}
752
753#ifdef NOT_USED
754static int
755max2hw_vres(Mustek_PP_CIS_dev *dev, int dist)
756{
757   return (int)((dist * dev->CIS.hw_vres) / dev->desc->dev->maxres + 0.5);
758}
759#endif
760
761static int
762max2cis_hres(Mustek_PP_CIS_dev *dev, int dist)
763{
764   return (int)((dist * dev->CIS.cisRes) / dev->desc->dev->maxres + 0.5);
765}
766
767static int
768cis2max_res(Mustek_PP_CIS_dev *dev, int dist)
769{
770   return (int)((dist * dev->desc->dev->maxres) / dev->CIS.cisRes + 0.5);
771}
772
773#ifdef NOT_USED
774static int
775hw2max_vres(Mustek_PP_CIS_dev *dev, int dist)
776{
777   return (int)((dist * dev->desc->dev->maxres) / dev->CIS.hw_vres + 0.5);
778}
779#endif
780
781/******************************************************************************
782 * Attempts to extract the current bank no.
783 *****************************************************************************/
784static void
785cis_get_bank_count(Mustek_PP_CIS_dev *dev)
786{
787   dev->bank_count = (Mustek_PP_1015_read_reg(dev, MA1015R_BANK_COUNT) & 0x7);
788   if (dev->CIS.use8KBank) dev->bank_count >>= 1;
789}
790
791/******************************************************************************
792 * Triggers a bank switch (I assume).
793 *****************************************************************************/
794static void
795cis_set_sti(Mustek_PP_CIS_dev *dev)
796{
797   SANEI_PA4S2_WRITEBYTE(dev->desc->fd, 3, 0xFF);
798   dev->bank_count++;
799   dev->bank_count &= (dev->CIS.use8KBank == SANE_TRUE) ? 3 : 7;
800}
801
802/******************************************************************************
803 * Wait till the bank with a given number becomes available.
804 *****************************************************************************/
805static SANE_Bool
806cis_wait_bank_change (Mustek_PP_CIS_dev * dev, int bankcount)
807{
808  struct timeval start, end;
809  unsigned long diff;
810  int firsttime = 1;
811
812  gettimeofday (&start, NULL);
813
814  do
815    {
816      if (1 /*niceload*/)
817	{
818	  if (firsttime)
819	    firsttime = 0;
820	  else
821	    usleep (10);	/* for a little nicer load */
822	}
823      cis_get_bank_count (dev);
824
825      gettimeofday (&end, NULL);
826      diff = (end.tv_sec * 1000 + end.tv_usec / 1000) -
827	(start.tv_sec * 1000 + start.tv_usec / 1000);
828
829    }
830  while ((dev->bank_count != bankcount) && (diff < MUSTEK_PP_CIS_WAIT_BANK));
831
832  if (dev->bank_count != bankcount && dev->desc->state != STATE_CANCELLED)
833  {
834     u_char tmp;
835     tmp = Mustek_PP_1015_read_reg(dev, 3);
836     DBG(2, "cis_wait_bank_change: Missed a bank: got %d [%s], "
837            "wanted %d, waited %d msec\n",
838             dev->bank_count, Mustek_PP_1015_show_val(tmp), bankcount,
839             MUSTEK_PP_CIS_WAIT_BANK);
840  }
841
842   return dev->bank_count == bankcount ? SANE_TRUE : SANE_FALSE;
843}
844
845/******************************************************************************
846 * Configure the CIS for a given resolution.
847 *
848 * CIS scanners seem to have 2 modes:
849 *
850 *   low resolution (50-300 DPI) and
851 *   high resolution (300-600 DPI).
852 *
853 * Depending on the resolution requested by the user, the scanner is used
854 * in high or low resolution mode. In high resolution mode, the motor step
855 * sizes are also reduced by a factor of two.
856 *
857 *****************************************************************************/
858static void
859cis_set_dpi_value (Mustek_PP_CIS_dev * dev)
860{
861   u_char val = 0;
862
863   if (dev->model == MUSTEK_PP_CIS1200PLUS)
864   {
865      /* Toshiba CIS: only 600 DPI + decimation */
866      switch (dev->CIS.hw_hres)
867      {
868         case 75:
869            val = 0x48; /* 1/8 */
870            break;
871         case 100:
872            val = 0x08; /* 1/6 */
873            break;
874         case 200:
875            val = 0x00; /* 1/3 */
876            break;
877         case 300:
878            val = 0x50; /* 2/4 */
879            break;
880         case 400:
881            val = 0x10; /* 2/3 */
882            break;
883         case 600:
884            val = 0x20; /* 3/3 */
885            break;
886         default:
887            assert (0);
888      }
889   }
890   else
891   {
892      /* Canon CIS: sensor can use 300 or 600 DPI */
893      switch (dev->CIS.hw_hres)
894      {
895         case 50:
896            val = 0x08; /* 1/6 */
897            break;
898         case 100:
899            val = 0x00; /* 1/3 */
900            break;
901         case 200:
902            val = 0x10; /* 2/3 */
903            break;
904         case 300:
905            val = 0x20; /* 3/3 */
906            break;
907         case 400:
908            val = 0x10; /* 2/3 */
909            break;
910         case 600:
911            val = 0x20; /* 3/3 */
912            break;
913         default:
914            assert (0);
915      }
916   }
917
918   Mustek_PP_1015_write_reg(dev, MA1015W_DPI_CONTROL, val | 0x04);
919
920   DBG (4, "cis_set_dpi_value: dpi: %d -> value 0x%02x\n", dev->CIS.hw_hres, val);
921}
922
923static void
924cis_set_ccd_channel (Mustek_PP_CIS_dev * dev)
925{
926
927   SANE_Byte codes[] = { 0x84, 0x44, 0xC4 };
928   SANE_Byte chancode;
929
930   assert (dev->CIS.channel < 3);
931
932   chancode = codes[dev->CIS.channel];
933
934   /*
935      The TWAIN driver sets an extra bit in lineart mode.
936      When I do this too, I don't see any effect on the image.
937      Moreover, for 1 resolution, namely 400 dpi, the bank counter seems
938      to behave strangely, and the synchronization get completely lost.
939      I guess the software conversion from gray to lineart is good enough,
940      so I'll leave it like that.
941
942      if (dev->CIS.setParameters)
943      {
944         chancode |= (dev->desc->mode == MODE_BW) ? 0x20: 0;
945      }
946   */
947
948   SANEI_PA4S2_WRITEBYTE (dev->desc->fd, 6, chancode);
949
950#ifdef M1015_TRACE_REGS
951   dev->CIS.regs.channel = chancode;
952#endif
953}
954
955static void
956cis_config_ccd (Mustek_PP_CIS_dev * dev)
957{
958   SANE_Int skipCount, byteCount;
959
960   if (dev->CIS.res != 0)
961     dev->CIS.hres_step =
962       SANE_FIX ((float) dev->CIS.hw_hres / (float) dev->CIS.res);
963
964   /* CIS:  <= 300 dpi -> 0x86
965             > 300 dpi -> 0x96 */
966
967   if (dev->CIS.cisRes == 600)
968      SANEI_PA4S2_WRITEBYTE (dev->desc->fd, 6, 0x96);
969   else
970      SANEI_PA4S2_WRITEBYTE (dev->desc->fd, 6, 0x86);
971
972   cis_set_dpi_value(dev);
973
974   if (dev->CIS.setParameters)
975   {
976      dev->CIS.channel = dev->desc->mode == MODE_COLOR ?
977                         MUSTEK_PP_CIS_CHANNEL_RED : MUSTEK_PP_CIS_CHANNEL_GRAY;
978   }
979   else
980   {
981      dev->CIS.channel = MUSTEK_PP_CIS_CHANNEL_GRAY;
982   }
983
984   cis_set_ccd_channel (dev);
985
986   Mustek_PP_1015_write_reg (dev, MA1015W_POWER_ON_DELAY, 0xAA);
987   Mustek_PP_1015_write_reg (dev, MA1015W_CCD_TIMING,     0x05);
988   Mustek_PP_1015_write_reg (dev, MA1015W_CCD_TIMING_ADJ, 0x00);
989
990   Mustek_PP_1015_send_command (dev, 0x45);	/* or 0x05 for no 8kbank */
991
992   /*
993    * Unknown sequence.
994    * Seems to be always the same during configuration, independent of the
995    * mode and the resolution.
996    */
997   CIS_CLEAR_FULLFLAG(dev);
998   CIS_INC_READ(dev);
999   CIS_CLEAR_READ_BANK(dev);
1000   CIS_CLEAR_WRITE_ADDR(dev);
1001   CIS_CLEAR_WRITE_BANK(dev);
1002   CIS_CLEAR_TOGGLE(dev);
1003
1004   /*
1005    # SkipImage = expressed in max resolution (600 DPI)
1006    #
1007    # Formulas
1008    #
1009    #  <= 300 DPI:
1010    #
1011    #  Skip = 67 + skipimage/2
1012    #
1013    #   Skip1 = Skip / 32
1014    #   Skip2 = Skip % 32
1015    #
1016    #  Bytes = Skip2 * hw_hres/300 + (imagebytes * hw_hres/res) + 2
1017    #
1018    #  > 300 DPI
1019    #
1020    #  Skip = 67 + skipimage
1021    #
1022    #   Skip1 = Skip / 32
1023    #   Skip2 = Skip % 32
1024    #
1025    #  Bytes = Skip2*hw_hres/600 + (imagebytes * hw_hres/res) + 2
1026    #
1027   */
1028
1029   skipCount = 67; /* Hardware parameter - fixed */
1030
1031   if (dev->CIS.setParameters == SANE_TRUE)
1032   {
1033      /*
1034       * It seems that the TWAIN driver always adds 2 mm extra. When I do the
1035       * inverse calculation from the parameters that driver sends, I always
1036       * get a difference of exactly 2mm, at every resolution and for
1037       * different positions of the scan area. Moreover, when I don't add this
1038       * offset, the resulting scan seems to start 2mm to soon.
1039       * I can't find this back in the backend of the TWAIN driver, but I
1040       * assume that this 2mm offset is taken care off at the higher levels.
1041       */
1042      DBG(4, "cis_config_ccd: Skip count: %d\n",  skipCount);
1043      skipCount += max2cis_hres(dev, dev->CIS.skipimagebytes);
1044      DBG(4, "cis_config_ccd: Skip count: %d (cis res: %d)\n",  skipCount,
1045             dev->CIS.cisRes);
1046      skipCount += (int)(2.0/25.4*dev->CIS.cisRes);
1047      DBG(4, "cis_config_ccd: Skip count: %d\n",  skipCount);
1048
1049      Mustek_PP_1015_write_reg (dev, MA1015W_SKIP_COUNT, skipCount / 32);
1050      DBG(4, "cis_config_ccd: Skip count: %d (x32)\n",  skipCount / 32);
1051   }
1052   else
1053   {
1054      Mustek_PP_1015_write_reg (dev, MA1015W_SKIP_COUNT, 0);
1055      DBG(4, "cis_config_ccd: Skip count: 67 (x32)\n");
1056   }
1057
1058   skipCount %= 32;
1059   skipCount = cis2max_res(dev, skipCount);  /* Back to max res */
1060
1061   Mustek_PP_1015_write_reg(dev, MA1015W_EXPOSE_TIME, dev->CIS.exposeTime);
1062
1063   DBG(4, "cis_config_ccd: skipcount: %d imagebytes: %d\n", skipCount, dev->CIS.imagebytes);
1064   /* set_initial_skip_1015 (dev); */
1065   if (dev->CIS.setParameters == SANE_TRUE)
1066   {
1067      Mustek_PP_1015_write_reg(dev, MA1015W_EXPOSE_TIME, dev->CIS.exposeTime);
1068      Mustek_PP_1015_write_reg(dev, MA1015W_POWER_ON_DELAY,   0xAA);
1069      /* The TWAIN drivers always sends the same value: 0x96 */
1070      Mustek_PP_1015_write_reg3(dev, MA1015W_RED_REF, 0x96, 0x96, 0x96);
1071      dev->CIS.adjustskip = max2hw_hres(dev, skipCount);
1072      byteCount = max2hw_hres(dev, skipCount + dev->CIS.imagebytes) + 2;
1073      dev->CIS.setParameters = SANE_FALSE;
1074   }
1075   else
1076   {
1077      dev->CIS.adjustskip = 0;
1078      byteCount = max2hw_hres(dev, skipCount);
1079   }
1080   DBG(4, "cis_config_ccd: adjust skip: %d bytecount: %d\n",
1081          dev->CIS.adjustskip, byteCount);
1082
1083   Mustek_PP_1015_write_reg2(dev, MA1015W_BYTE_COUNT_HB,
1084                             byteCount >> 8, byteCount & 0xFF);
1085
1086   cis_get_bank_count (dev);
1087   DBG(5, "cis_config_ccd: done\n");
1088}
1089
1090static SANE_Bool
1091cis_wait_motor_stable (Mustek_PP_CIS_dev * dev)
1092{
1093   static struct timeval timeoutVal;
1094   SANE_Bool ret =
1095      Mustek_PP_1015_wait_bit (dev, MA1015R_MOTOR, MA1015B_MOTOR_STABLE,
1096                               SANE_FALSE, 0);
1097#ifdef HAVE_SYS_SELECT_H
1098   if (dev->engine_delay > 0)
1099   {
1100      timeoutVal.tv_sec = 0;
1101      timeoutVal.tv_usec = dev->engine_delay*1000;
1102      select(0, NULL, NULL, NULL, &timeoutVal);
1103   }
1104#endif
1105   return ret;
1106}
1107
1108static void
1109cis_motor_forward (Mustek_PP_CIS_dev * dev)
1110{
1111   SANE_Byte control;
1112
1113   if (dev->model == MUSTEK_PP_CIS600)
1114   {
1115      switch (dev->CIS.hw_vres)
1116      {
1117         case 150:
1118            control = 0x7B;
1119            break;
1120         case 300:
1121            control = 0x73;
1122            break;
1123         case 600:
1124            control = 0x13;
1125            break;
1126         default:
1127            exit(1);
1128      }
1129   }
1130   else
1131   {
1132      switch (dev->CIS.hw_vres)
1133      {
1134         case 300:
1135            control = 0x7B;
1136            break;
1137         case 600:
1138            control = 0x73;
1139            break;
1140         case 1200:
1141            control = 0x13;
1142            break;
1143         default:
1144            exit(1);
1145      }
1146   }
1147
1148#if MUSTEK_PP_CIS_MOTOR_REVERSE == 1
1149   control ^= 0x10;
1150#endif
1151
1152   DBG(4, "cis_motor_forward: @%d dpi: 0x%02X.\n", dev->CIS.hw_vres, control);
1153   if (!cis_wait_motor_stable (dev))
1154      return;
1155
1156   Mustek_PP_1015_write_reg(dev, MA1015W_MOTOR_CONTROL, control);
1157}
1158
1159static void
1160cis_move_motor (Mustek_PP_CIS_dev * dev, SANE_Int steps) /* steps @ maxres */
1161{
1162   /* Note: steps is expressed at maximum resolution */
1163   SANE_Byte fullStep = 0x13, biStep = 0x73, quadStep = 0x7B;
1164   SANE_Int fullSteps, biSteps, quadSteps;
1165   /*
1166    * During a multi-step feed, the expose time is fixed. The value depends
1167    * on the type of the motor (600/1200 CP)
1168    */
1169   SANE_Byte savedExposeTime = dev->CIS.exposeTime;
1170   dev->CIS.exposeTime = 85;
1171
1172   DBG(4, "cis_move_motor: Moving motor %d steps.\n", steps);
1173
1174   /* Just in case ... */
1175   if (steps < 0)
1176   {
1177      DBG(1, "cis_move_motor: trying to move negative steps: %d\n", steps);
1178      steps = 0; /* We must go through the configuration procedure */
1179   }
1180
1181   /*
1182    * Using the parameter settings for the 600 CP on a 1200 CP scanner
1183    * doesn't work: the engine doesn't move and makes a sharp noise, which
1184    * doesn't sound too healthy. It could be harmful to the motor !
1185    * Apparently, the same happens on a real 600 CP (reported by Disma
1186    * Goggia), so it's probably better to always use the 1200 CP settings.
1187    */
1188   dev->CIS.exposeTime <<= 1;
1189   cis_config_ccd(dev);
1190   dev->CIS.exposeTime = savedExposeTime;
1191
1192   /*
1193    * This is a minor speed optimization: when we are using the high
1194    * resolution mode, long feeds (eg, to move to a scan area at the bottom
1195    * of the page) can be made almost twice as fast by using double motor
1196    * steps as much as possible.
1197    * It is possible, though, that fast skipping (which is the default) is
1198    * not very accurate on some scanners. Therefore, the user can disable
1199    * this through the configuration file.
1200    */
1201
1202   fullSteps = steps  & 1;
1203   biSteps = steps >> 1;
1204   if (dev->fast_skip) {
1205      quadSteps = biSteps >> 1;
1206      biSteps &= 1;
1207   }
1208   else {
1209      quadSteps = 0;
1210   }
1211
1212   M1015_DISPLAY_REGS(dev, "Before move");
1213
1214#if MUSTEK_PP_CIS_MOTOR_REVERSE == 1
1215   fullStep ^= 0x10;
1216   biStep ^= 0x10;
1217   quadStep ^= 0x10;
1218#endif
1219
1220   DBG(4, "cis_move_motor: 4x%d 2x%d 1x%d\n", quadSteps, biSteps, fullSteps);
1221   /* Note: the TWAIN driver opens the motor control register only
1222      once before the loop, and closes it after the loop. I've tried this
1223      too, but it resulted in inaccurate skip distances; therefore, the
1224      motor control register is now opened and closed for each step. */
1225
1226   while (quadSteps-- > 0 && dev->desc->state != STATE_CANCELLED)
1227   {
1228      cis_wait_motor_stable (dev);
1229      Mustek_PP_1015_write_reg(dev, MA1015W_MOTOR_CONTROL, quadStep);
1230   }
1231
1232   while (biSteps-- > 0 && dev->desc->state != STATE_CANCELLED)
1233   {
1234      cis_wait_motor_stable (dev);
1235      Mustek_PP_1015_write_reg(dev, MA1015W_MOTOR_CONTROL, biStep);
1236   }
1237
1238   while (fullSteps-- > 0 && dev->desc->state != STATE_CANCELLED)
1239   {
1240      cis_wait_motor_stable (dev);
1241      Mustek_PP_1015_write_reg(dev, MA1015W_MOTOR_CONTROL, fullStep);
1242   }
1243}
1244
1245static void
1246cis_set_et_pd_sti (Mustek_PP_CIS_dev * dev)
1247{
1248   Mustek_PP_1015_write_reg(dev, MA1015W_EXPOSE_TIME,
1249                                 dev->CIS.exposeTime);
1250   Mustek_PP_1015_write_reg(dev, MA1015W_POWER_ON_DELAY,
1251                                 dev->CIS.powerOnDelay[dev->CIS.channel]);
1252   cis_set_ccd_channel (dev);
1253   cis_set_sti (dev);
1254}
1255
1256/*
1257 * Prepare the scanner for catching the next channel and, if necessary,
1258 * move the head one step further.
1259 */
1260static SANE_Bool
1261cis_wait_next_channel (Mustek_PP_CIS_dev * dev)
1262{
1263   int moveAtChannel = dev->desc->mode == MODE_COLOR ?
1264                       MUSTEK_PP_CIS_CHANNEL_BLUE : MUSTEK_PP_CIS_CHANNEL_GRAY;
1265
1266   if (!cis_wait_bank_change (dev, dev->bank_count))
1267   {
1268      DBG(2, "cis_wait_next_channel: Could not get next bank.\n");
1269      return SANE_FALSE;
1270   }
1271
1272   moveAtChannel = (dev->desc->mode == MODE_COLOR) ?
1273                    MUSTEK_PP_CIS_CHANNEL_BLUE : MUSTEK_PP_CIS_CHANNEL_GRAY;
1274
1275   if (dev->CIS.channel == moveAtChannel && !dev->CIS.dontMove)
1276   {
1277      cis_motor_forward (dev);
1278   }
1279
1280   cis_set_et_pd_sti (dev);
1281
1282   if (dev->desc->mode == MODE_COLOR)
1283   {
1284      ++dev->CIS.channel;
1285      dev->CIS.channel %= 3;
1286   }
1287
1288   return SANE_TRUE;
1289}
1290
1291/*
1292 * Wait for the device to be ready for scanning. Cycles through the different
1293 * channels and sets the parameters (only green channel in gray/lineart).
1294 */
1295static SANE_Bool
1296cis_wait_read_ready (Mustek_PP_CIS_dev * dev)
1297{
1298   int channel;
1299   dev->CIS.dontIncRead = SANE_TRUE;
1300
1301   dev->CIS.channel =  dev->desc->mode == MODE_COLOR ?
1302                       MUSTEK_PP_CIS_CHANNEL_RED : MUSTEK_PP_CIS_CHANNEL_GRAY;
1303
1304   for (channel = 0; channel < 3; ++channel)
1305   {
1306      if (!cis_wait_next_channel(dev)) return SANE_FALSE;
1307   }
1308   return SANE_TRUE;
1309}
1310
1311static int
1312delay_read (int delay)
1313{
1314   /*
1315    * A (very) smart compiler may complete optimize the delay loop away. By
1316    * adding some difficult data dependencies, we can try to prevent this.
1317    */
1318   static int prevent_removal, i;
1319   for (i = 0; i<delay; ++i)
1320   {
1321      prevent_removal = sqrt(prevent_removal+1.); /* Just waste some cycles */
1322   }
1323   return prevent_removal; /* another data dependency */
1324}
1325
1326/*
1327** Reads one line of pixels
1328*/
1329static void
1330cis_read_line_low_level (Mustek_PP_CIS_dev * dev, SANE_Byte * buf,
1331                         SANE_Int pixel, SANE_Byte * calib_low,
1332                         SANE_Byte * calib_hi, SANE_Int * gamma)
1333{
1334   u_char color;
1335   int ctr, skips = dev->CIS.adjustskip, cval;
1336   int bpos = 0;
1337   SANE_Byte low_val = 0, hi_val = 255;
1338
1339   if (pixel <= 0)
1340      return;
1341
1342   SANEI_PA4S2_READBEGIN (dev->desc->fd, 1);
1343
1344   while(skips-- >= 0)
1345   {
1346      if (dev->CIS.delay) delay_read(dev->CIS.delay);
1347      SANEI_PA4S2_READBYTE (dev->desc->fd, &color);
1348   }
1349
1350   if (dev->CIS.hw_hres == dev->CIS.res)
1351   {
1352      /* One-to one mapping */
1353      DBG (6, "cis_read_line_low_level: one-to-one\n");
1354      for (ctr = 0; ctr < pixel; ctr++)
1355      {
1356         if (dev->CIS.delay) delay_read(dev->CIS.delay);
1357         SANEI_PA4S2_READBYTE (dev->desc->fd, &color);
1358
1359	 cval = color;
1360
1361         if (calib_low) {
1362           low_val = calib_low[ctr] ;
1363         }
1364
1365         if (calib_hi) {
1366           hi_val = calib_hi[ctr] ;
1367         }
1368
1369         cval  -= low_val ;
1370         cval <<= 8 ;
1371         cval  /= hi_val-low_val ;
1372
1373         if (cval < 0)         cval = 0;
1374         else if (cval > 255)  cval = 255;
1375
1376         if (gamma)
1377	    cval = gamma[cval];
1378
1379	 buf[ctr] = cval;
1380      }
1381   }
1382   else if (dev->CIS.hw_hres > dev->CIS.res)
1383   {
1384      /* Sub-sampling */
1385
1386      int pos = 0;
1387      DBG (6, "cis_read_line_low_level: sub-sampling\n");
1388      ctr = 0;
1389      do
1390      {
1391         if (dev->CIS.delay) delay_read(dev->CIS.delay);
1392         SANEI_PA4S2_READBYTE (dev->desc->fd, &color);
1393
1394         cval = color;
1395         if (ctr < (pos >> SANE_FIXED_SCALE_SHIFT))
1396	 {
1397	    ctr++;
1398	    continue;
1399	 }
1400
1401         ctr++;
1402         pos += dev->CIS.hres_step;
1403
1404         if (calib_low) {
1405           low_val = calib_low[bpos] ;
1406         }
1407
1408         if (calib_hi) {
1409           hi_val = calib_hi[bpos] ;
1410         }
1411         cval  -= low_val ;
1412         cval <<= 8 ;
1413         cval  /= hi_val-low_val ;
1414
1415         if (cval < 0)         cval = 0 ;
1416         else if (cval > 255)  cval = 255 ;
1417
1418         if (gamma) cval = gamma[cval];
1419
1420         buf[bpos++] = cval;
1421      }
1422      while (bpos < pixel);
1423   }
1424   else
1425   {
1426      int calctr = 0;
1427      SANE_Int pos = 0, nextPos = 1;
1428      /* Step: eg: 600 DPI -> 700 DPI -> hres_step = 6/7 -> step = 1/7 */
1429      SANE_Int step = SANE_FIX(1) - dev->CIS.hres_step;
1430
1431      /* Super-sampling */
1432      DBG (6, "cis_read_line_low_level: super-sampling\n");
1433      do
1434      {
1435         if (dev->CIS.delay) delay_read(dev->CIS.delay);
1436         SANEI_PA4S2_READBYTE (dev->desc->fd, &color);
1437
1438	 cval = color;
1439
1440         if (calib_low) {
1441           low_val = calib_low[calctr] ;
1442         }
1443
1444         if (calib_hi) {
1445           hi_val = calib_hi[calctr] ;
1446         }
1447
1448         if (++calctr >= dev->calib_pixels) {
1449            /* Avoid array boundary violations due to rounding errors
1450               (due to the incremental calculation, the current position
1451               may be inaccurate to up to two pixels, so we may need to
1452               read a few extra bytes -> use the last calibration value) */
1453            calctr = dev->calib_pixels - 1;
1454            DBG (3, "cis_read_line_low_level: calibration overshoot\n");
1455         }
1456
1457         cval  -= low_val ;
1458         cval <<= 8 ;
1459         cval  /= hi_val-low_val ;
1460
1461         if (cval < 0)         cval = 0 ;
1462         else if (cval > 255)  cval = 255 ;
1463
1464         if (gamma)
1465	    cval = gamma[cval];
1466
1467         pos += step;
1468
1469         if ((pos >> SANE_FIXED_SCALE_SHIFT) >= nextPos)
1470         {
1471            nextPos++;
1472
1473            /* Insert an interpolated value */
1474            buf[bpos] = (buf[bpos-1] + cval)/2; /* Interpolate */
1475            ++bpos;
1476
1477            /* Store the plain value, but only if we still need pixels */
1478            if (bpos < pixel)
1479               buf[bpos++] = cval;
1480
1481            pos += step; /* Take interpolated value into account for pos */
1482         }
1483         else
1484         {
1485  	    buf[bpos++] = cval;
1486         }
1487      }
1488      while (bpos < pixel);
1489   }
1490
1491   SANEI_PA4S2_READEND (dev->desc->fd);
1492   DBG (6, "cis_read_line_low_level: done\n");
1493}
1494
1495static SANE_Bool
1496cis_read_line (Mustek_PP_CIS_dev * dev, SANE_Byte* buf, SANE_Int pixel,
1497               SANE_Bool raw)
1498{
1499   if (!dev->CIS.dontIncRead)
1500      CIS_INC_READ(dev);
1501   else
1502      dev->CIS.dontIncRead = SANE_FALSE;
1503
1504
1505   if (raw)
1506   {
1507      /* No color correction; raw data */
1508      cis_read_line_low_level (dev, buf, pixel, NULL, NULL, NULL);
1509   }
1510   else
1511   {
1512      /* Color correction */
1513      cis_read_line_low_level (dev, buf, pixel,
1514                               dev->calib_low[dev->CIS.channel],
1515                               dev->calib_hi[dev->CIS.channel],
1516                               (dev->desc->val[OPT_CUSTOM_GAMMA].w ?
1517                               dev->desc->gamma_table[dev->CIS.channel] : NULL));
1518   }
1519
1520   return cis_wait_next_channel(dev);
1521}
1522
1523static void
1524cis_get_next_line (Mustek_PP_CIS_dev * dev, SANE_Byte * buf)
1525{
1526   SANE_Byte *dest, *tmpbuf = dev->tmpbuf;
1527   int ctr, channel, first, last, stride, step = dev->CIS.line_step;
1528   SANE_Byte gotline;
1529
1530   if (dev->desc->mode == MODE_COLOR)
1531   {
1532      first = MUSTEK_PP_CIS_CHANNEL_RED;
1533      last = MUSTEK_PP_CIS_CHANNEL_BLUE;
1534      stride = 3;
1535   }
1536   else
1537   {
1538      first = MUSTEK_PP_CIS_CHANNEL_GRAY;
1539      last = MUSTEK_PP_CIS_CHANNEL_GRAY;
1540      stride = 1;
1541   }
1542
1543   gotline = SANE_FALSE;
1544   do
1545   {
1546      dev->ccd_line++;
1547      if ((dev->line_diff >> SANE_FIXED_SCALE_SHIFT) != dev->ccd_line)
1548      {
1549         cis_motor_forward (dev);
1550         continue;
1551      }
1552
1553      dev->line_diff += step;
1554
1555      for (channel = first; channel <= last; ++channel)
1556      {
1557         if (!cis_read_line(dev, tmpbuf, dev->desc->params.pixels_per_line,
1558                            SANE_FALSE))
1559            return;
1560
1561         dest = buf + channel - first;
1562         for (ctr = 0; ctr < dev->desc->params.pixels_per_line; ctr++)
1563         {
1564	    *dest = tmpbuf[ctr];
1565            dest += stride;
1566         }
1567      }
1568      gotline = SANE_TRUE;
1569   }
1570   while (!gotline && dev->desc->state != STATE_CANCELLED);
1571}
1572
1573static void
1574cis_get_grayscale_line (Mustek_PP_CIS_dev * dev, SANE_Byte * buf)
1575{
1576   cis_get_next_line(dev, buf);
1577}
1578
1579static void
1580cis_get_lineart_line (Mustek_PP_CIS_dev * dev, SANE_Byte * buf)
1581{
1582   int ctr;
1583   SANE_Byte gbuf[MUSTEK_PP_CIS_MAX_H_PIXEL * 2];
1584
1585   cis_get_grayscale_line (dev, gbuf);
1586   memset (buf, 0xFF, dev->desc->params.bytes_per_line);
1587
1588   for (ctr = 0; ctr < dev->desc->params.pixels_per_line; ctr++)
1589      buf[ctr >> 3] ^= ((gbuf[ctr] > dev->bw_limit) ? (1 << (7 - ctr % 8)) : 0);
1590}
1591
1592static void
1593cis_get_color_line (Mustek_PP_CIS_dev * dev, SANE_Byte * buf)
1594{
1595   cis_get_next_line(dev, buf);
1596}
1597
1598
1599/******************************************************************************
1600 * Saves the state of the device during reset and calibration.
1601 *****************************************************************************/
1602static void
1603cis_save_state (Mustek_PP_CIS_dev * dev)
1604{
1605   dev->Saved_CIS = dev->CIS;
1606}
1607
1608/******************************************************************************
1609 * Restores the state of the device after reset and calibration.
1610 *****************************************************************************/
1611static void
1612cis_restore_state (Mustek_PP_CIS_dev * dev)
1613{
1614   dev->CIS = dev->Saved_CIS;
1615}
1616
1617#define CIS_TOO_BRIGHT 1
1618#define CIS_OK         0
1619#define CIS_TOO_DARK  -1
1620
1621static int
1622cis_check_result(SANE_Byte* buffer, int pixel)
1623{
1624   int i, maxVal = 0;
1625
1626   for (i=0;i<pixel;++i)
1627      if (buffer[i] > maxVal) maxVal = buffer[i];
1628
1629   if (maxVal > 250) return CIS_TOO_BRIGHT;
1630   if (maxVal < 240) return CIS_TOO_DARK;
1631   return CIS_OK;
1632}
1633
1634static SANE_Bool
1635cis_maximize_dynamic_range(Mustek_PP_CIS_dev * dev)
1636{
1637   /* The device is in its final configuration already. */
1638   int i, j, pixel, channel, minExposeTime, first, last;
1639   SANE_Byte powerOnDelayLower[3], powerOnDelayUpper[3], exposeTime[3];
1640   SANE_Byte buf[3][MUSTEK_PP_CIS_MAX_H_PIXEL];
1641   SANE_Int pixels = dev->calib_pixels;
1642
1643   DBG(3, "cis_maximize_dynamic_range: starting\n");
1644
1645   for (channel = 0; channel < 3; ++channel)
1646   {
1647      exposeTime[channel] = 254;
1648      dev->CIS.powerOnDelay[channel] = 170;
1649      powerOnDelayLower[channel] = 1;
1650      powerOnDelayUpper[channel] = 254;
1651   }
1652   dev->CIS.setParameters  = SANE_TRUE;
1653   dev->CIS.exposeTime     = exposeTime[MUSTEK_PP_CIS_CHANNEL_GREEN];
1654   cis_config_ccd(dev);
1655
1656   M1015_DISPLAY_REGS(dev, "before maximizing dynamic range");
1657   dev->CIS.dontMove = SANE_TRUE; /* Don't move while calibrating */
1658
1659   if (!cis_wait_read_ready(dev) && dev->desc->state != STATE_CANCELLED)
1660   {
1661      DBG(2, "cis_maximize_dynamic_range: DEVICE NOT READY!\n");
1662      return SANE_FALSE;
1663   }
1664
1665   if (dev->desc->mode == MODE_COLOR)
1666   {
1667      first = MUSTEK_PP_CIS_CHANNEL_RED;
1668      last  = MUSTEK_PP_CIS_CHANNEL_BLUE;
1669   }
1670   else
1671   {
1672      first = MUSTEK_PP_CIS_CHANNEL_GRAY;
1673      last  = MUSTEK_PP_CIS_CHANNEL_GRAY;
1674   }
1675
1676   dev->CIS.channel = first;
1677
1678   /* Perform a kind of binary search. In the worst case, we should find
1679      the optimal power delay values after 8 iterations */
1680   for( i=0; i<8; i++)
1681   {
1682      for (channel = first; channel <= last; ++channel)
1683      {
1684         dev->CIS.powerOnDelay[channel] = (powerOnDelayLower[channel] +
1685                                           powerOnDelayUpper[channel]) / 2;
1686      }
1687      Mustek_PP_1015_write_reg(dev, MA1015W_POWER_ON_DELAY,
1688                               dev->CIS.powerOnDelay[1]); /* Green */
1689
1690      for (pixel = 0; pixel < pixels; ++pixel)
1691      {
1692         buf[0][pixel] = buf[1][pixel] = buf[2][pixel] = 255;
1693      }
1694
1695      /* Scan 4 lines, but ignore the first 3 ones. */
1696      for (j = 0; j < 4; ++j)
1697      {
1698         for (channel = first; channel <= last; ++channel)
1699         {
1700            if (!cis_read_line(dev, &buf[channel][0], pixels,
1701                               /* raw = */ SANE_TRUE))
1702               return SANE_FALSE;
1703         }
1704      }
1705
1706      for (channel = first; channel <= last; ++channel)
1707      {
1708         switch (cis_check_result(buf[channel], pixels))
1709         {
1710            case CIS_TOO_BRIGHT:
1711               powerOnDelayLower[channel] = dev->CIS.powerOnDelay[channel];
1712               break;
1713
1714            case CIS_TOO_DARK:
1715               powerOnDelayUpper[channel] = dev->CIS.powerOnDelay[channel];
1716               break;
1717
1718            default:
1719               break;
1720         }
1721      }
1722      DBG (4, "cis_maximize_dynamic_range: power on delay %3d %3d %3d\n",
1723           dev->CIS.powerOnDelay[0], dev->CIS.powerOnDelay[1],
1724           dev->CIS.powerOnDelay[2]);
1725   }
1726   dev->CIS.dontMove = SANE_FALSE;
1727
1728   DBG (3, "cis_maximize_dynamic_range: power on delay %3d %3d %3d\n",
1729           dev->CIS.powerOnDelay[0], dev->CIS.powerOnDelay[1],
1730           dev->CIS.powerOnDelay[2]);
1731
1732   minExposeTime = (dev->CIS.hw_hres <= 300) ? 170 : 253;
1733
1734   for (channel = first; channel <= last; ++channel)
1735   {
1736      dev->CIS.powerOnDelay[channel] = (powerOnDelayLower[channel] +
1737                                        powerOnDelayUpper[channel]) / 2;
1738      exposeTime[channel] -= dev->CIS.powerOnDelay[channel] - 1;
1739      dev->CIS.powerOnDelay[channel] = 1;
1740
1741      if (exposeTime[channel] < minExposeTime)
1742      {
1743         dev->CIS.powerOnDelay[channel] +=
1744            minExposeTime - exposeTime[channel];
1745         exposeTime[channel] = minExposeTime;
1746      }
1747   }
1748
1749   dev->CIS.exposeTime = exposeTime[MUSTEK_PP_CIS_CHANNEL_GREEN];
1750
1751   DBG (3, "cis_maximize_dynamic_range: expose time: %3d\n", exposeTime[1]);
1752   DBG (3, "cis_maximize_dynamic_range: power on delay %3d %3d %3d\n",
1753           dev->CIS.powerOnDelay[0], dev->CIS.powerOnDelay[1],
1754           dev->CIS.powerOnDelay[2]);
1755
1756   /*
1757    * Short the calibration. Temporary, to find out what is wrong with
1758    * the calibration on a 600 CP.
1759    *
1760   dev->CIS.exposeTime = 170;
1761   dev->CIS.powerOnDelay[0] = 120;
1762   dev->CIS.powerOnDelay[1] = 120;
1763   dev->CIS.powerOnDelay[2] = 120;
1764   */
1765   return SANE_TRUE;
1766}
1767
1768static SANE_Bool
1769cis_measure_extremes(Mustek_PP_CIS_dev * dev, SANE_Byte* calib[3],
1770		     SANE_Int pixels, SANE_Int first, SANE_Int last)
1771{
1772   SANE_Byte buf[3][MUSTEK_PP_CIS_MAX_H_PIXEL];
1773   SANE_Byte min[3][MUSTEK_PP_CIS_MAX_H_PIXEL];
1774   SANE_Byte max[3][MUSTEK_PP_CIS_MAX_H_PIXEL];
1775   SANE_Int  sum[3][MUSTEK_PP_CIS_MAX_H_PIXEL];
1776   int channel, cnt, p;
1777
1778   memset((void*)&min, 255, 3*MUSTEK_PP_CIS_MAX_H_PIXEL*sizeof(SANE_Byte));
1779   memset((void*)&max,   0, 3*MUSTEK_PP_CIS_MAX_H_PIXEL*sizeof(SANE_Byte));
1780   memset((void*)&sum,   0, 3*MUSTEK_PP_CIS_MAX_H_PIXEL*sizeof(SANE_Int));
1781
1782   dev->CIS.channel = first;
1783
1784   /* Purge the banks first (there's always a 3-cycle delay) */
1785   for (channel = first; channel <= last; ++channel)
1786   {
1787      if (!cis_read_line(dev, &buf[channel%3][0], pixels,
1788                         /* raw = */ SANE_TRUE))
1789         return SANE_FALSE;
1790   }
1791   --dev->CIS.skipsToOrigin;
1792
1793   for (cnt = 0; cnt < MUSTEK_PP_CIS_AVERAGE_COUNT + 2; ++cnt)
1794   {
1795      for (channel = first; channel <= last; ++channel)
1796      {
1797         DBG(4, "cis_measure_extremes: Reading line %d - channel %d\n",
1798                cnt, channel);
1799         if (!cis_read_line(dev, &buf[channel][0], pixels,
1800                            /* raw = */ SANE_TRUE))
1801            return SANE_FALSE;
1802
1803         for (p = 0; p < pixels; ++p)
1804         {
1805            SANE_Byte val = buf[channel][p];
1806            if (val < min[channel][p]) min[channel][p] = val;
1807            if (val > max[channel][p]) max[channel][p] = val;
1808            sum[channel][p] += val;
1809         }
1810      }
1811      --dev->CIS.skipsToOrigin;
1812   }
1813   DBG(4, "cis_measure_extremes: Averaging\n");
1814   for (channel = first; channel <= last; ++channel)
1815   {
1816      /* Ignore the extreme values and take the average of the others. */
1817      for (p = 0; p < pixels; ++p)
1818      {
1819         sum[channel][p] -= min[channel][p] + max[channel][p];
1820         sum[channel][p] /= MUSTEK_PP_CIS_AVERAGE_COUNT;
1821         if (calib[channel]) calib[channel][p] = sum[channel][p];
1822      }
1823   }
1824   DBG(4, "cis_measure_extremes: Done\n");
1825   return SANE_TRUE;
1826}
1827
1828static SANE_Bool
1829cis_normalize_ranges(Mustek_PP_CIS_dev * dev)
1830{
1831   SANE_Byte cal_low, cal_hi ;
1832   SANE_Byte powerOnDelay[3] ;
1833   SANE_Int pixels = dev->calib_pixels;
1834   SANE_Int channel, p, first, last;
1835
1836   if (dev->desc->mode == MODE_COLOR)
1837   {
1838      first = MUSTEK_PP_CIS_CHANNEL_RED;
1839      last  = MUSTEK_PP_CIS_CHANNEL_BLUE;
1840   }
1841   else
1842   {
1843      first = MUSTEK_PP_CIS_CHANNEL_GRAY;
1844      last  = MUSTEK_PP_CIS_CHANNEL_GRAY;
1845   }
1846
1847   DBG(3, "cis_normalize_ranges: Measuring high extremes\n");
1848   /* Measure extremes with normal lighting */
1849   if (!cis_measure_extremes(dev, dev->calib_hi, pixels, first, last)) {
1850      return SANE_FALSE;
1851   }
1852
1853   /* Measure extremes without lighting */
1854   for (channel=first; channel<=last; ++channel) {
1855      powerOnDelay[channel] = dev->CIS.powerOnDelay[channel];
1856      dev->CIS.powerOnDelay[channel] = dev->CIS.exposeTime;
1857   }
1858
1859   DBG(3, "cis_normalize_ranges: Measuring low extremes\n");
1860   if (!cis_measure_extremes(dev, dev->calib_low, pixels, first, last)) {
1861      return SANE_FALSE;
1862   }
1863
1864   /* Restore settings */
1865   for (channel=first; channel<=last; ++channel) {
1866      dev->CIS.powerOnDelay[channel] = powerOnDelay[channel];
1867   }
1868
1869   /* Make sure calib_hi is greater than calib_low */
1870   for (channel = first; channel <= last; ++channel) {
1871     for (p = 0; p<pixels; p++) {
1872       if (dev->calib_low[channel]) {
1873         cal_low = dev->calib_low[channel][p];
1874       } else {
1875         cal_low = 0;
1876       }
1877       if (dev->calib_hi[channel]) {
1878         cal_hi = dev->calib_hi[channel][p];
1879       } else {
1880         cal_hi = 255;
1881       }
1882       if (cal_hi <= cal_low) {
1883         if(cal_hi<255) {
1884           /* calib_hi exists, else cal_hi would be 255 */
1885           dev->calib_hi[channel][p] = cal_low+1;
1886         } else {
1887           /* calib_low exists, else cal_low would be 0, < 255  */
1888           dev->calib_low[channel][p] = cal_hi-1;
1889         }
1890       }
1891     }
1892   }
1893   DBG(3, "cis_normalize_ranges: calibration done\n");
1894   return SANE_TRUE;
1895}
1896
1897/*
1898 * This routine measures the time that we have to wait between reading
1899 * to pixels from the scanner. Especially at low resolutions, but also
1900 * for narrow-width scans at high resolutions, reading too fast cause
1901 * color stability problems.
1902 * This routine sends a test pattern to the scanner memory banks and tries
1903 * to measure how fast it can be retrieved without errors.
1904 * The same is done by the TWAIN driver (TESTIO.CPP:TestDelay).
1905 */
1906static SANE_Bool
1907cis_measure_delay(Mustek_PP_CIS_dev * dev)
1908{
1909   SANE_Byte buf[2][2048];
1910   unsigned i, j, d;
1911   int saved_res;
1912   SANE_Bool error = SANE_FALSE;
1913
1914   CIS_CLEAR_FULLFLAG(dev);
1915   CIS_CLEAR_WRITE_ADDR(dev);
1916   CIS_CLEAR_WRITE_BANK(dev);
1917   CIS_INC_READ(dev);
1918   CIS_CLEAR_READ_BANK(dev);
1919
1920   M1015_DISPLAY_REGS(dev, "Before delay measurement");
1921   assert(dev->CIS.adjustskip == 0);
1922
1923   /* Sawtooth */
1924   for (i=0; i<2048; ++i)
1925   {
1926      buf[0][i] = i % 255; /* Why 255 ? Seems to have no real importance */
1927   }
1928
1929   Mustek_PP_1015_write_reg_start(dev, MA1015W_SRAM_SOURCE_PC);
1930   for (i=0; i<2048; ++i)
1931   {
1932      Mustek_PP_1015_write_reg_val(dev, buf[0][i]);
1933   }
1934   Mustek_PP_1015_write_reg_stop(dev);
1935
1936   /* Bank offset measurement */
1937   dev->CIS.delay = 0; /* Initialize to zero, measure next */
1938
1939   saved_res = dev->CIS.res;
1940   dev->CIS.res = dev->CIS.hw_hres;
1941
1942   /*
1943    * Note: the TWAIN driver seems to have a fast EPP mode too. That one is
1944    * tried first, and then they try the normal mode. I haven't figured out
1945    * yet how the fast mode works, so I'll only check the normal mode for now.
1946    * Moreover, from the behaviour that I've witnessed from the TWAIN driver,
1947    * I must conclude that the fast mode probably doesn't work on my computer,
1948    * so I can't test it anyhow.
1949    */
1950   /* Gradually increase the delay till we have no more errors */
1951   for (d = 0; d < 75 /* 255 */  && dev->desc->state != STATE_CANCELLED; d += 5)
1952   {
1953      dev->CIS.delay = d;
1954
1955      /*
1956       * We read the line 5 times to make sure that all garbage is flushed.
1957       */
1958      for (i=0; i<5; ++i)
1959      {
1960         CIS_INC_READ(dev);
1961         CIS_CLEAR_READ_BANK(dev);
1962         cis_read_line_low_level (dev, &buf[1][0], 2048, NULL, NULL, NULL);
1963         if (dev->desc->state == STATE_CANCELLED) return SANE_FALSE;
1964      }
1965
1966      error = SANE_FALSE;
1967      /* Check 100 times whether we can read without errors. */
1968      for (i=0; i<100 && !error; ++i)
1969      {
1970         CIS_INC_READ(dev);
1971         CIS_CLEAR_READ_BANK(dev);
1972         cis_read_line_low_level (dev, &buf[1][0], 2048, NULL, NULL, NULL);
1973         if (dev->desc->state == STATE_CANCELLED) return SANE_FALSE;
1974
1975         for (j=0; j<2048; ++j)
1976         {
1977            if (buf[0][j] != buf[1][j])
1978            {
1979               error = SANE_TRUE;
1980               break;
1981            }
1982         }
1983      }
1984
1985      DBG (3, "cis_measure_delay: delay %d\n", dev->CIS.delay);
1986      if (!error)
1987         break;
1988   }
1989
1990   dev->CIS.res = saved_res;
1991
1992   if (error)
1993   {
1994      fprintf(stderr, "mustek_pp_cis: failed to measure delay.\n");
1995      fprintf(stderr, "Buffer contents:\n");
1996      for (j = 0; j < 20; ++j)
1997      {
1998         fprintf(stderr, "%d ", buf[1][j]);
1999      }
2000      fprintf(stderr, "\n");
2001      dev->CIS.delay = 0;
2002   }
2003
2004   DBG (3, "cis_measure_delay: delay %d\n", dev->CIS.delay);
2005   return SANE_TRUE;
2006}
2007
2008static void
2009cis_motor_control (Mustek_PP_CIS_dev * dev, u_char control)
2010{
2011   cis_wait_motor_stable (dev);
2012   Mustek_PP_1015_write_reg(dev, MA1015W_MOTOR_CONTROL, control);
2013}
2014
2015static void
2016cis_return_home (Mustek_PP_CIS_dev * dev, SANE_Bool nowait)
2017{
2018   SANE_Byte savedExposeTime = dev->CIS.exposeTime;
2019   DBG(4, "cis_return_home: returning home; nowait: %d\n", nowait);
2020   /* During a return-home, the expose time is fixed. */
2021   dev->CIS.exposeTime = 170;
2022   cis_config_ccd(dev);
2023   dev->CIS.exposeTime = savedExposeTime;
2024
2025   cis_motor_control (dev, 0xEB);
2026
2027   if (nowait == SANE_FALSE)
2028      Mustek_PP_1015_wait_bit(dev, MA1015R_MOTOR, MA1015B_MOTOR_HOME,
2029                              SANE_TRUE, 1000);
2030}
2031
2032/******************************************************************************
2033 * Does a full reset of the device, ie. configures the CIS to a default
2034 * resolution of 300 DPI (in high or low resolution mode, depending on the
2035 * resolution requested by the user).
2036 *****************************************************************************/
2037static void
2038cis_reset_device (Mustek_PP_CIS_dev * dev)
2039{
2040   DBG(4, "cis_reset_device: resetting device\n");
2041   dev->CIS.adjustskip         = 0;
2042   dev->CIS.dontIncRead        = SANE_TRUE;
2043   dev->CIS.dontMove           = SANE_FALSE;
2044
2045   cis_save_state(dev);
2046
2047   dev->CIS.hw_hres            = 300;
2048   dev->CIS.channel            = MUSTEK_PP_CIS_CHANNEL_GREEN;
2049   dev->CIS.setParameters      = SANE_FALSE;
2050   dev->CIS.exposeTime         = 0xAA;
2051
2052   cis_config_ccd (dev);
2053
2054   cis_restore_state(dev);
2055
2056}
2057
2058static SANE_Bool
2059cis_calibrate (Mustek_PP_CIS_dev * dev)
2060{
2061   int i, saved_res = dev->CIS.res, saved_vres = dev->CIS.hw_vres;
2062
2063   /*
2064    * Flow of operation observed from the twain driver
2065    * (it is assumed that the lamp is at the origin, and that the CIS is
2066    * configured for 300 DPI, ie. cis_reset_device has been called.)
2067    *
2068    *  - Reset the device and return the lamp to its home position
2069    *
2070    *  - Unknown short sequence
2071    *
2072    *  - Send a sawtooth-like pattern to one of the memory banks.
2073    *
2074    *  - Repetitive read_line of 2048 bytes, interleaved with an unknown
2075    *    command. The number varies between 102 and 170 times, but there
2076    *    doesn't seem to be any correlation with the current mode of the
2077    *    scanner, so I assume that the exact number isn't really relevant.
2078    *    The values that are read are the one that were sent to the bank,
2079    *    rotated by 1 byte in my case.
2080    *
2081    *
2082    *    It seems that the width of the black border is being measured at
2083    *    this stage, possibly multiple times till it stabilizes.
2084    *    I assume that the buffer is read 100 times to allow the lamp to
2085    *    warm up and that the width of the black border is then being
2086    *    measured till it stabilizes. That would explain the minimum number
2087    *    of 102 iterations that I've seen.
2088    *
2089    *  - reset the device
2090    *
2091    *  - move the motor 110 steps forward. The TWAIN driver moves 90 steps,
2092    *    and I've used 90 steps for a long time too, but occasionally,
2093    *    90 steps is a fraction to short to reach the start of the
2094    *    calibration strip (the motor movements are not very accurate;
2095    *    an offset of 1 mm is not unusual). Therefore, I've increased it to
2096    *    110 steps. This gives us an additional 1.6 mm slack, which should
2097    *    prevent calibration errors.
2098    *    (Note that the MUSTEK_PP_CIS_????CP_DEFAULT_SKIP constants have to
2099    *    be adjusted if the number of steps is altered.)
2100    *
2101    *  - configure the CIS : actual resolution + set parameters
2102    *
2103    */
2104
2105   /*
2106    * We must make sure that we are in the scanning state; otherwise we may
2107    * still be in the canceled state from a previous scan (even if terminated
2108    * normally), and the whole calibration would go wrong.
2109    */
2110   dev->desc->state = STATE_SCANNING;
2111
2112   cis_reset_device (dev);
2113   cis_return_home (dev, SANE_FALSE);  /* Wait till it's home */
2114
2115   /* Use maximum resolution during calibration; otherwise we may calibrate
2116      past the calibration strip. */
2117   dev->CIS.hw_vres = dev->desc->dev->maxres;
2118   /* This field remembers how many steps we still have to go @ max res */
2119   dev->CIS.skipsToOrigin = dev->top_skip; /*max2hw_vres(dev, dev->top_skip); */
2120
2121   if (!cis_measure_delay(dev))
2122      return SANE_FALSE;
2123
2124   cis_reset_device (dev);
2125
2126   /* Move motor 110 steps @ 300 DPI */
2127   Mustek_PP_1015_write_reg_start(dev, MA1015W_MOTOR_CONTROL);
2128   for (i=0; i<110; ++i)
2129   {
2130      if (dev->model == MUSTEK_PP_CIS600)
2131      {
2132         Mustek_PP_1015_write_reg_val (dev, 0x73);
2133      }
2134      else
2135      {
2136         Mustek_PP_1015_write_reg_val (dev, 0x7B);
2137      }
2138      cis_wait_motor_stable (dev);
2139   }
2140   Mustek_PP_1015_write_reg_stop(dev);
2141
2142   /* Next, we maximize the dynamic range of the scanner. During calibration
2143      we don't want to extrapolate, so we limit the resolution if necessary */
2144
2145   if (dev->CIS.hw_hres < dev->CIS.res)
2146      dev->CIS.res = dev->CIS.hw_hres;
2147
2148   if (!cis_maximize_dynamic_range(dev))
2149      return SANE_FALSE;
2150
2151   if (!cis_normalize_ranges(dev))
2152      return SANE_FALSE;
2153
2154   dev->CIS.res = saved_res;
2155   dev->CIS.hw_vres = saved_vres;
2156
2157   /* Convert steps back to max res size, which are used during skipping */
2158/*   dev->CIS.skipsToOrigin = hw2max_vres(dev, dev->CIS.skipsToOrigin); */
2159
2160   /* Move to the origin */
2161   DBG(3, "cis_calibrate: remaining skips to origin @maxres: %d\n",
2162          dev->CIS.skipsToOrigin);
2163   cis_move_motor(dev, dev->CIS.skipsToOrigin);
2164
2165   if (dev->calib_mode)
2166   {
2167      /* In calibration mode, we scan the interior of the scanner before the
2168         glass plate in order to find the position of the calibration strip
2169         and the start of the glass plate. */
2170      DBG(3, "cis_calibrate: running in calibration mode. Returning home.\n");
2171      cis_return_home (dev, SANE_FALSE);  /* Wait till it's home */
2172   }
2173
2174   return dev->desc->state != STATE_CANCELLED ? SANE_TRUE : SANE_FALSE;
2175
2176}
2177
2178/******************************************************************************
2179 ******************************************************************************
2180 ***                           Mustek PP interface                          ***
2181 ******************************************************************************
2182 *****************************************************************************/
2183
2184/******************************************************************************
2185* Init                                                                        *
2186******************************************************************************/
2187
2188/* Shared initialization routine */
2189static SANE_Status cis_attach(SANE_String_Const port,
2190                              SANE_String_Const name,
2191                              SANE_Attach_Callback attach,
2192                              SANE_Int driverNo,
2193                              SANE_Int info)
2194{
2195   int fd;
2196   SANE_Status status;
2197   u_char asic;
2198
2199   status = sanei_pa4s2_open (port, &fd);
2200
2201   if (status != SANE_STATUS_GOOD)
2202   {
2203      SANE_Status altStatus;
2204      SANE_String_Const altPort;
2205
2206      DBG (2, "cis_attach: couldn't attach to `%s' (%s)\n", port,
2207           sane_strstatus (status));
2208
2209      /* Make migration to libieee1284 painless for users that used
2210         direct io in the past */
2211           if (strcmp(port, "0x378") == 0) altPort = "parport0";
2212      else if (strcmp(port, "0x278") == 0) altPort = "parport1";
2213      else if (strcmp(port, "0x3BC") == 0) altPort = "parport2";
2214      else return status;
2215
2216      DBG (2, "cis_attach: trying alternative port name: %s\n", altPort);
2217
2218      altStatus = sanei_pa4s2_open (altPort, &fd);
2219      if (altStatus != SANE_STATUS_GOOD)
2220      {
2221           DBG (2, "cis_attach: couldn't attach to alternative port `%s' "
2222              "(%s)\n", altPort, sane_strstatus (altStatus));
2223           return status; /* Return original status, not alternative status */
2224      }
2225   }
2226
2227   M1015_START_LL;
2228   M1015_START_HL;
2229
2230
2231   sanei_pa4s2_enable (fd, SANE_TRUE);
2232   SANEI_PA4S2_READBEGIN (fd, 0);
2233   SANEI_PA4S2_READBYTE (fd, &asic);
2234   SANEI_PA4S2_READEND (fd);
2235   sanei_pa4s2_enable (fd, SANE_FALSE);
2236
2237   sanei_pa4s2_close (fd);
2238
2239   if (asic != 0xA5) /* Identifies the MA1015 chipset */
2240   {
2241      /* CIS driver only works for MA1015 chipset */
2242      DBG (2, "cis_attach: asic id (0x%02x) not recognized\n", asic);
2243      return SANE_STATUS_INVAL;
2244   }
2245
2246   DBG (3, "cis_attach: device %s attached\n", name);
2247   DBG (3, "cis_attach: asic 0x%02x\n", asic);
2248
2249   return attach(port, name, driverNo, info);
2250}
2251
2252SANE_Status cis600_drv_init(SANE_Int options, SANE_String_Const port,
2253		SANE_String_Const name, SANE_Attach_Callback attach)
2254{
2255   if (options != CAP_NOTHING)
2256      return SANE_STATUS_INVAL;
2257
2258   return cis_attach(port, name, attach, MUSTEK_PP_CIS600, MUSTEK_PP_CIS600);
2259}
2260
2261SANE_Status cis1200_drv_init(SANE_Int options, SANE_String_Const port,
2262		SANE_String_Const name, SANE_Attach_Callback attach)
2263{
2264   if (options != CAP_NOTHING)
2265      return SANE_STATUS_INVAL;
2266
2267   return cis_attach(port, name, attach, MUSTEK_PP_CIS1200, MUSTEK_PP_CIS1200);
2268}
2269
2270SANE_Status cis1200p_drv_init(SANE_Int options, SANE_String_Const port,
2271		SANE_String_Const name, SANE_Attach_Callback attach)
2272{
2273   if (options != CAP_NOTHING)
2274      return SANE_STATUS_INVAL;
2275
2276   return cis_attach(port, name, attach, MUSTEK_PP_CIS1200PLUS, MUSTEK_PP_CIS1200PLUS);
2277}
2278
2279/******************************************************************************
2280* Capabilities                                                                *
2281******************************************************************************/
2282void cis_drv_capabilities(SANE_Int info, SANE_String *model,
2283                          SANE_String *vendor, SANE_String *type,
2284                          SANE_Int *maxres, SANE_Int *minres,
2285                          SANE_Int *maxhsize, SANE_Int *maxvsize,
2286                          SANE_Int *caps)
2287{
2288   *vendor = strdup("Mustek");
2289   *type = strdup("flatbed scanner");
2290   *caps = CAP_NOTHING;
2291
2292   switch(info)
2293   {
2294      case MUSTEK_PP_CIS600:
2295        *model = strdup("600CP");
2296        *maxres = 600;
2297        *minres = 50;
2298        *maxhsize = MUSTEK_PP_CIS_MAX_H_PIXEL;
2299        *maxvsize = MUSTEK_PP_CIS_MAX_V_PIXEL;
2300        break;
2301      case MUSTEK_PP_CIS1200:
2302        *model = strdup("1200CP");
2303        *maxres = 1200;
2304        *minres = 50;
2305        *maxhsize = MUSTEK_PP_CIS_MAX_H_PIXEL*2;
2306        *maxvsize = MUSTEK_PP_CIS_MAX_V_PIXEL*2;
2307        break;
2308      case MUSTEK_PP_CIS1200PLUS:
2309        *model = strdup("1200CP+");
2310        *maxres = 1200;
2311        *minres = 50;
2312        *maxhsize = MUSTEK_PP_CIS_MAX_H_PIXEL*2;
2313        *maxvsize = MUSTEK_PP_CIS_MAX_V_PIXEL*2;
2314        break;
2315   }
2316}
2317
2318/******************************************************************************
2319* Open                                                                        *
2320******************************************************************************/
2321SANE_Status cis_drv_open (SANE_String port, SANE_Int caps, SANE_Int *fd)
2322{
2323   SANE_Status status;
2324
2325   if (caps != CAP_NOTHING)
2326   {
2327      DBG (1, "cis_drv_open: called with unknown capabilities (0x%02X)\n", caps);
2328      return SANE_STATUS_INVAL;
2329   }
2330
2331   DBG (3, "cis_drv_open: called for port %s\n", port);
2332
2333   status = sanei_pa4s2_open (port, fd);
2334
2335   if (status != SANE_STATUS_GOOD)
2336   {
2337      SANE_Status altStatus;
2338      SANE_String_Const altPort;
2339
2340      DBG (2, "cis_attach: couldn't attach to `%s' (%s)\n", port,
2341           sane_strstatus (status));
2342
2343      /* Make migration to libieee1284 painless for users that used
2344         direct io in the past */
2345           if (strcmp(port, "0x378") == 0) altPort = "parport0";
2346      else if (strcmp(port, "0x278") == 0) altPort = "parport1";
2347      else if (strcmp(port, "0x3BC") == 0) altPort = "parport2";
2348      else return status;
2349
2350      DBG (2, "cis_attach: trying alternative port name: %s\n", altPort);
2351
2352      altStatus = sanei_pa4s2_open (altPort, fd);
2353      if (altStatus != SANE_STATUS_GOOD)
2354      {
2355           DBG (2, "cis_attach: couldn't attach to alternative port `%s' "
2356              "(%s)\n", altPort, sane_strstatus (altStatus));
2357           return status; /* Return original status, not alternative status */
2358      }
2359   }
2360
2361   return SANE_STATUS_GOOD;
2362}
2363
2364/******************************************************************************
2365* Setup                                                                       *
2366******************************************************************************/
2367void cis_drv_setup (SANE_Handle hndl)
2368{
2369   Mustek_pp_Handle *dev = hndl;
2370   Mustek_PP_CIS_dev *cisdev;
2371   cisdev = (Mustek_PP_CIS_dev*)malloc(sizeof(Mustek_PP_CIS_dev));
2372   if (cisdev == NULL)
2373   {
2374      DBG (2, "cis_drv_setup: not enough memory for device descriptor\n");
2375      sanei_pa4s2_close (dev->fd);
2376      return;
2377   }
2378   memset(cisdev, 0, sizeof(Mustek_PP_CIS_dev));
2379   DBG(3, "cis_drv_setup: cis device allocated\n");
2380
2381   dev->lamp_on = 0;
2382   dev->priv = cisdev;
2383
2384   cisdev->desc = dev;
2385   cisdev->model = dev->dev->info;
2386   cisdev->CIS.hw_hres = 300;
2387   cisdev->CIS.cisRes = 300;
2388   cisdev->CIS.hw_vres = 300;
2389
2390   /* Default values for configurable parameters; configuration file
2391      may override them. */
2392   cisdev->fast_skip = SANE_TRUE;
2393   cisdev->bw_limit = 127;
2394   cisdev->calib_mode = SANE_FALSE;
2395   cisdev->engine_delay = 0;
2396   if (cisdev->model == MUSTEK_PP_CIS600)
2397   {
2398      cisdev->top_skip = MUSTEK_PP_CIS_600CP_DEFAULT_SKIP;
2399   }
2400   else
2401   {
2402      cisdev->top_skip = MUSTEK_PP_CIS_1200CP_DEFAULT_SKIP;
2403   }
2404}
2405
2406/******************************************************************************
2407* Config                                                                      *
2408******************************************************************************/
2409SANE_Status cis_drv_config(SANE_Handle hndl, SANE_String_Const optname,
2410	 		   SANE_String_Const optval)
2411{
2412   Mustek_pp_Handle *dev = hndl;
2413   Mustek_PP_CIS_dev *cisdev = dev->priv;
2414   int value = 0;
2415   double dvalue = 0;
2416   DBG (3, "cis_drv_cfg option: %s=%s\n", optname, optval ? optval : "");
2417   if (!strcmp(optname, "top_adjust"))
2418   {
2419      if (!optval)
2420      {
2421         DBG (1, "cis_drv_config: missing value for option top_adjust\n");
2422         return SANE_STATUS_INVAL;
2423      }
2424      dvalue = atof(optval);
2425
2426      /* An adjustment of +/- 5 mm should be sufficient and safe */
2427      if (dvalue < -5.0)
2428      {
2429         DBG (1, "cis_drv_config: value for option top_adjust too small: "
2430                 "%.2f < -5; limiting to -5 mm\n", dvalue);
2431         dvalue = -5.0;
2432      }
2433      if (dvalue > 5.0)
2434      {
2435         DBG (1, "cis_drv_config: value for option top_adjust too large: "
2436                 "%.2f > 5; limiting to 5 mm\n", dvalue);
2437         dvalue = 5.0;
2438      }
2439      /* In practice, there is a lower bound on the value that can be used,
2440         but if the top_skip value is smaller than that value, the only result
2441         will be that the driver tries to move the head a negative number
2442         of steps after calibration. The move routine just ignores negative
2443         steps, so no harm can be done. */
2444      cisdev->top_skip += MM_TO_PIXEL(dvalue, dev->dev->maxres);
2445      DBG (3, "cis_drv_config: setting top skip value to %d\n",
2446              cisdev->top_skip);
2447
2448      /* Just to be cautious; we don't want the head to hit the bottom */
2449      if (cisdev->top_skip > 600) cisdev->top_skip = 600;
2450      if (cisdev->top_skip < -600) cisdev->top_skip = -600;
2451   }
2452   else if (!strcmp(optname, "slow_skip"))
2453   {
2454      if (optval)
2455      {
2456         DBG (1, "cis_drv_config: unexpected value for option slow_skip\n");
2457         return SANE_STATUS_INVAL;
2458      }
2459      DBG (3, "cis_drv_config: disabling fast skipping\n");
2460      cisdev->fast_skip = SANE_FALSE;
2461   }
2462   else if (!strcmp(optname, "bw"))
2463   {
2464      if (!optval)
2465      {
2466         DBG (1, "cis_drv_config: missing value for option bw\n");
2467         return SANE_STATUS_INVAL;
2468      }
2469      value = atoi(optval);
2470      if (value < 0 || value > 255)
2471      {
2472         DBG (1, "cis_drv_config: value for option bw out of range: "
2473                 "%d < 0 or %d > 255\n", value, value);
2474         return SANE_STATUS_INVAL;
2475      }
2476      cisdev->bw_limit = value;
2477   }
2478   else if (!strcmp(optname, "calibration_mode"))
2479   {
2480      if (optval)
2481      {
2482         DBG (1, "cis_drv_config: unexpected value for option calibration_mode\n");
2483         return SANE_STATUS_INVAL;
2484      }
2485      DBG (3, "cis_drv_config: using calibration mode\n");
2486      cisdev->calib_mode = SANE_TRUE;
2487   }
2488   else if (!strcmp(optname, "engine_delay"))
2489   {
2490      if (!optval)
2491      {
2492         DBG (1, "cis_drv_config: missing value for option engine_delay\n");
2493         return SANE_STATUS_INVAL;
2494      }
2495      value = atoi(optval);
2496      if (value < 0 || value > 100) /* 100 ms is already pretty slow */
2497      {
2498         DBG (1, "cis_drv_config: value for option engine_delay out of range: "
2499                 "%d < 0 or %d > 100\n", value, value);
2500         return SANE_STATUS_INVAL;
2501      }
2502      cisdev->engine_delay = value;
2503   }
2504   else
2505   {
2506      DBG (1, "cis_drv_config: unknown options %s\n", optname);
2507      return SANE_STATUS_INVAL;
2508   }
2509   return SANE_STATUS_GOOD;
2510}
2511
2512/******************************************************************************
2513* Close                                                                       *
2514******************************************************************************/
2515void cis_drv_close (SANE_Handle hndl)
2516{
2517   Mustek_pp_Handle *dev = hndl;
2518   Mustek_PP_CIS_dev *cisdev = dev->priv;
2519   DBG (3, "cis_close: resetting device.\n");
2520   sanei_pa4s2_enable (dev->fd, SANE_TRUE);
2521   cis_reset_device (cisdev);
2522   DBG (3, "cis_close: returning home.\n");
2523   cis_return_home (cisdev, SANE_TRUE); /* Don't wait */
2524   DBG (3, "cis_close: disabling fd.\n");
2525   sanei_pa4s2_enable (dev->fd, SANE_FALSE);
2526   DBG (3, "cis_close: closing fd.\n");
2527   sanei_pa4s2_close (dev->fd);
2528   DBG (3, "cis_close: done.\n");
2529   DBG (6, "cis_close: lamp_on: %d\n", (int)dev->lamp_on);
2530   M1015_STOP_LL;
2531   M1015_STOP_HL;
2532}
2533
2534/******************************************************************************
2535* Start                                                                       *
2536******************************************************************************/
2537SANE_Status cis_drv_start (SANE_Handle hndl)
2538{
2539   Mustek_pp_Handle *dev = hndl;
2540   Mustek_PP_CIS_dev *cisdev = dev->priv;
2541   SANE_Int pixels = dev->params.pixels_per_line;
2542
2543   if (!cisdev)
2544   {
2545      DBG (2, "cis_drv_start: not enough memory for device\n");
2546      return SANE_STATUS_NO_MEM;
2547   }
2548
2549   cisdev->CIS.exposeTime = 0xAA;
2550   cisdev->CIS.setParameters = SANE_FALSE;
2551   cisdev->CIS.use8KBank = SANE_TRUE;
2552   cisdev->CIS.imagebytes = dev->bottomX - dev->topX;
2553   cisdev->CIS.skipimagebytes = dev->topX;
2554
2555   cisdev->CIS.res = dev->res;
2556
2557   DBG (3, "cis_drv_start: %d dpi\n", dev->res);
2558
2559   if (dev->res <= 50 && cisdev->model != MUSTEK_PP_CIS1200PLUS)
2560   {
2561     cisdev->CIS.hw_hres = 50;
2562   }
2563   else if (dev->res <= 75 && cisdev->model == MUSTEK_PP_CIS1200PLUS)
2564   {
2565     cisdev->CIS.hw_hres = 75;
2566   }
2567   else if (dev->res <= 100)
2568   {
2569     cisdev->CIS.hw_hres = 100;
2570   }
2571   else if (dev->res <= 200)
2572   {
2573     cisdev->CIS.hw_hres = 200;
2574   }
2575   else if (dev->res <= 300)
2576   {
2577     cisdev->CIS.hw_hres = 300;
2578   }
2579   else
2580   {
2581      if (cisdev->model == MUSTEK_PP_CIS600)
2582      {
2583         cisdev->CIS.hw_hres = 300; /* Limit for 600 CP */
2584      }
2585      else if (dev->res <= 400)
2586      {
2587   	 cisdev->CIS.hw_hres = 400;
2588      }
2589      else
2590      {
2591	 cisdev->CIS.hw_hres = 600; /* Limit for 1200 CP/CP+ */
2592      }
2593   }
2594
2595   if (cisdev->model == MUSTEK_PP_CIS600)
2596   {
2597      if (dev->res <= 150)
2598      {
2599         cisdev->CIS.hw_vres = 150;
2600      }
2601      else if (dev->res <= 300)
2602      {
2603         cisdev->CIS.hw_vres = 300;
2604      }
2605      else
2606      {
2607         cisdev->CIS.hw_vres = 600;
2608      }
2609   }
2610   else
2611   {
2612      if (dev->res <= 300)
2613      {
2614         cisdev->CIS.hw_vres = 300;
2615      }
2616      else if (dev->res <= 600)
2617      {
2618         cisdev->CIS.hw_vres = 600;
2619      }
2620      else
2621      {
2622         cisdev->CIS.hw_vres = 1200;
2623      }
2624   }
2625
2626   if (cisdev->model == MUSTEK_PP_CIS600 ||
2627       (cisdev->model == MUSTEK_PP_CIS1200 && dev->res <= 300))
2628     cisdev->CIS.cisRes = 300;
2629   else
2630     cisdev->CIS.cisRes = 600;
2631
2632   /* Calibration only makes sense for hardware pixels, not for interpolated
2633      pixels, so we limit the number of calibration pixels to the maximum
2634      number of hardware pixels corresponding to the selected area */
2635   if (dev->res > cisdev->CIS.hw_hres)
2636      cisdev->calib_pixels = (pixels * cisdev->CIS.hw_hres) / dev->res;
2637   else
2638      cisdev->calib_pixels = pixels;
2639
2640   DBG (3, "cis_drv_start: hres: %d vres: %d cisres: %d\n",
2641            cisdev->CIS.hw_hres, cisdev->CIS.hw_vres, cisdev->CIS.cisRes);
2642
2643   sanei_pa4s2_enable (dev->fd, SANE_TRUE);
2644
2645   cis_reset_device (cisdev);
2646   cis_return_home (cisdev, SANE_TRUE); /* Don't wait here */
2647
2648#ifdef M1015_TRACE_REGS
2649   {
2650      int i, j;
2651
2652      /*
2653       * Set all registers to -1 (uninitialized)
2654       */
2655      for (i=0; i<4; ++i)
2656      {
2657         cisdev->CIS.regs.in_regs[i] = -1;
2658         for (j=0; j<4; ++j)
2659         {
2660            cisdev->CIS.regs.out_regs[i][j] = -1;
2661         }
2662      }
2663
2664      cisdev->CIS.regs.channel = -1;
2665      /* These values have been read earlier. */
2666      cisdev->CIS.regs.in_regs[0] = 0xA5;
2667   }
2668#endif
2669
2670   cis_reset_device (cisdev);
2671   cis_return_home (cisdev, SANE_TRUE); /* no wait */
2672
2673   /* Allocate memory for temporary color buffer */
2674   cisdev->tmpbuf = malloc (pixels);
2675   if (cisdev->tmpbuf == NULL)
2676   {
2677      sanei_pa4s2_enable (dev->fd, SANE_FALSE);
2678      DBG (2, "cis_drv_start: not enough memory for temporary buffer\n");
2679      free(cisdev);
2680      dev->priv = NULL;
2681      return SANE_STATUS_NO_MEM;
2682   }
2683
2684   /* Allocate memory for calibration; calibrating interpolated pixels
2685      makes no sense */
2686   if (pixels > (dev->dev->maxhsize >> 1))
2687      pixels = (dev->dev->maxhsize >> 1);
2688
2689   cisdev->calib_low[1] = malloc (pixels);
2690   cisdev->calib_hi[1] = malloc (pixels);
2691
2692   if (cisdev->calib_low[1] == NULL || cisdev->calib_hi[1] == NULL)
2693   {
2694      free (cisdev->calib_low[1]); cisdev->calib_low[1] = NULL;
2695      free (cisdev->calib_hi[1]);  cisdev->calib_hi[1] = NULL;
2696      sanei_pa4s2_enable (dev->fd, SANE_FALSE);
2697      DBG (2, "cis_drv_start: not enough memory for calibration buffer\n");
2698      free(cisdev->tmpbuf); cisdev->tmpbuf = NULL;
2699      free(cisdev); dev->priv = NULL;
2700      return SANE_STATUS_NO_MEM;
2701   }
2702
2703   cisdev->calib_low[0] = NULL;
2704   cisdev->calib_low[2] = NULL;
2705   cisdev->calib_hi[0] = NULL;
2706   cisdev->calib_hi[2] = NULL;
2707   if (dev->mode == MODE_COLOR)
2708   {
2709      cisdev->calib_low[0] = malloc (pixels);
2710      cisdev->calib_low[2] = malloc (pixels);
2711      cisdev->calib_hi[0] = malloc (pixels);
2712      cisdev->calib_hi[2] = malloc (pixels);
2713
2714      if ((cisdev->calib_low[0] == NULL) || (cisdev->calib_low[2] == NULL) ||
2715          (cisdev->calib_hi[0] == NULL) || (cisdev->calib_hi[2] == NULL))
2716      {
2717         free (cisdev->calib_low[0]); cisdev->calib_low[0] = NULL;
2718	 free (cisdev->calib_low[1]); cisdev->calib_low[1] = NULL;
2719         free (cisdev->calib_low[2]); cisdev->calib_low[2] = NULL;
2720         free (cisdev->calib_hi[0]); cisdev->calib_hi[0] = NULL;
2721	 free (cisdev->calib_hi[1]); cisdev->calib_hi[1] = NULL;
2722         free (cisdev->calib_hi[2]); cisdev->calib_hi[2] = NULL;
2723         free(cisdev->tmpbuf); cisdev->tmpbuf = NULL;
2724         free(cisdev); dev->priv = NULL;
2725	 sanei_pa4s2_enable (dev->fd, SANE_FALSE);
2726	 DBG (2, "cis_drv_start: not enough memory for color calib buffer\n");
2727	 return SANE_STATUS_NO_MEM;
2728      }
2729   }
2730
2731   DBG (3, "cis_drv_start: executing calibration\n");
2732
2733   if (!cis_calibrate (cisdev))
2734   {
2735      free (cisdev->calib_low[0]); cisdev->calib_low[0] = NULL;
2736      free (cisdev->calib_low[1]); cisdev->calib_low[1] = NULL;
2737      free (cisdev->calib_low[2]); cisdev->calib_low[2] = NULL;
2738      free (cisdev->calib_hi[0]); cisdev->calib_hi[0] = NULL;
2739      free (cisdev->calib_hi[1]); cisdev->calib_hi[1] = NULL;
2740      free (cisdev->calib_hi[2]); cisdev->calib_hi[2] = NULL;
2741      free(cisdev->tmpbuf); cisdev->tmpbuf = NULL;
2742      free(cisdev); dev->priv = NULL;
2743      return SANE_STATUS_CANCELLED; /* Most likely cause */
2744   }
2745
2746/*   M1015_DISPLAY_REGS(dev, "after calibration"); */
2747
2748   cis_get_bank_count(cisdev);
2749
2750   cis_move_motor (cisdev, dev->topY); /* Measured in max resolution */
2751
2752   /* It is vital to reinitialize the scanner right before we start the
2753      real scanning. Otherwise the bank synchronization may have gotten lost
2754      by the time we reach the top of the scan area */
2755
2756   cisdev->CIS.setParameters = SANE_TRUE;
2757   cis_config_ccd(cisdev);
2758   cis_wait_read_ready(cisdev);
2759
2760   sanei_pa4s2_enable (dev->fd, SANE_FALSE);
2761
2762   cisdev->CIS.line_step =
2763     SANE_FIX ((float) cisdev->CIS.hw_vres / (float) cisdev->CIS.res);
2764
2765   /*
2766    * It is very important that line_diff is not initialized at zero !
2767    * If it is set to zero, the motor will keep on moving forever (or better,
2768    * till the scanner breaks).
2769    */
2770   cisdev->line_diff = cisdev->CIS.line_step;
2771   cisdev->ccd_line = 0;
2772   cisdev->line = 0;
2773   cisdev->lines_left = dev->params.lines;
2774
2775   dev->state = STATE_SCANNING;
2776
2777   DBG (3, "cis_drv_start: device ready for scanning\n");
2778
2779   return SANE_STATUS_GOOD;
2780}
2781
2782/******************************************************************************
2783* Read                                                                        *
2784******************************************************************************/
2785void cis_drv_read (SANE_Handle hndl, SANE_Byte *buffer)
2786{
2787   Mustek_pp_Handle *dev = hndl;
2788   Mustek_PP_CIS_dev *cisdev = dev->priv;
2789   DBG(6, "cis_drv_read: Reading line\n");
2790   sanei_pa4s2_enable (dev->fd, SANE_TRUE);
2791   switch (dev->mode)
2792   {
2793      case MODE_BW:
2794         cis_get_lineart_line(cisdev, buffer);
2795         break;
2796
2797      case MODE_GRAYSCALE:
2798         cis_get_grayscale_line(cisdev, buffer);
2799         break;
2800
2801      case MODE_COLOR:
2802         cis_get_color_line(cisdev, buffer);
2803         break;
2804   }
2805   sanei_pa4s2_enable (dev->fd, SANE_FALSE);
2806}
2807
2808/******************************************************************************
2809* Stop                                                                        *
2810******************************************************************************/
2811void cis_drv_stop (SANE_Handle hndl)
2812{
2813   Mustek_pp_Handle *dev = hndl;
2814   Mustek_PP_CIS_dev *cisdev = dev->priv;
2815
2816   /* device is scanning: return lamp and free buffers */
2817   DBG (3, "cis_drv_stop: stopping current scan\n");
2818   dev->state = STATE_CANCELLED;
2819
2820   DBG (9, "cis_drv_stop: enabling fd\n");
2821   sanei_pa4s2_enable (dev->fd, SANE_TRUE);
2822   Mustek_PP_1015_write_reg(cisdev, MA1015W_MOTOR_CONTROL, 0); /* stop */
2823   DBG (9, "cis_drv_stop: resetting device (1)\n");
2824   cis_reset_device (cisdev);
2825   DBG (9, "cis_drv_stop: returning home\n");
2826   cis_return_home (cisdev, SANE_TRUE); /* don't wait */
2827   DBG (9, "cis_drv_stop: resetting device (2)\n");
2828   cis_reset_device (cisdev);
2829   DBG (9, "cis_drv_stop: disabling fd\n");
2830   sanei_pa4s2_enable (dev->fd, SANE_FALSE);
2831   DBG (9, "cis_drv_stop: freeing buffers\n");
2832
2833   /* This is no good: canceling while the device is scanning and
2834      freeing the data buffers can result in illegal memory accesses if
2835      the device is still scanning in another thread. */
2836   free (cisdev->calib_low[1]); cisdev->calib_low[1] = NULL;
2837   free (cisdev->calib_hi[1]); cisdev->calib_hi[1] = NULL;
2838   free (cisdev->tmpbuf); cisdev->tmpbuf = NULL;
2839   DBG (3, "cis_drv_stop: freed green and temporary buffers\n");
2840
2841   if (cisdev->CIS.mode == MODE_COLOR)
2842   {
2843      free (cisdev->calib_low[0]); cisdev->calib_low[0] = NULL;
2844      free (cisdev->calib_low[2]); cisdev->calib_low[2] = NULL;
2845      free (cisdev->calib_hi[0]); cisdev->calib_hi[0] = NULL;
2846      free (cisdev->calib_hi[2]); cisdev->calib_hi[2] = NULL;
2847   }
2848   DBG (3, "cis_drv_stop: freed buffers\n");
2849   DBG (6, "cis_drv_stop: lamp_on: %d\n", (int)dev->lamp_on);
2850}
2851