xref: /third_party/backends/backend/epson2-ops.c (revision 141cc406)
1/*
2 * epson2.c - SANE library for Epson scanners.
3 *
4 * Based on Kazuhiro Sasayama previous
5 * Work on epson.[ch] file from the SANE package.
6 * Please see those files for additional copyrights.
7 *
8 * Copyright (C) 2006-09 Tower Technologies
9 * Author: Alessandro Zummo <a.zummo@towertech.it>
10 *
11 * This file is part of the SANE package.
12 *
13 * This program is free software; you can redistribute it and/or
14 * modify it under the terms of the GNU General Public License as
15 * published by the Free Software Foundation, version 2.
16 */
17
18#define DEBUG_DECLARE_ONLY
19
20#include "sane/config.h"
21
22#include <unistd.h>		/* sleep */
23#ifdef HAVE_SYS_SELECT_H
24#include <sys/select.h>
25#endif
26
27#include "byteorder.h"
28
29#include "epson2.h"
30#include "epson2-ops.h"
31
32#include "epson2-io.h"
33#include "epson2-commands.h"
34
35/*
36 *       request identity
37 *       |   request identity2
38 *       |   |   request status
39 *       |   |   |   request condition
40 *       |   |   |   |   set color mode
41 *       |   |   |   |   |   start scanning
42 *       |   |   |   |   |   |   set data format
43 *       |   |   |   |   |   |   |   set resolution
44 *       |   |   |   |   |   |   |   |   set zoom
45 *       |   |   |   |   |   |   |   |   |   set scan area
46 *       |   |   |   |   |   |   |   |   |   |   set brightness
47 *       |   |   |   |   |   |   |   |   |   |   |              set gamma
48 *       |   |   |   |   |   |   |   |   |   |   |              |   set halftoning
49 *       |   |   |   |   |   |   |   |   |   |   |              |   |   set color correction
50 *       |   |   |   |   |   |   |   |   |   |   |              |   |   |   initialize scanner
51 *       |   |   |   |   |   |   |   |   |   |   |              |   |   |   |   set speed
52 *       |   |   |   |   |   |   |   |   |   |   |              |   |   |   |   |   set lcount
53 *       |   |   |   |   |   |   |   |   |   |   |              |   |   |   |   |   |   mirror image
54 *       |   |   |   |   |   |   |   |   |   |   |              |   |   |   |   |   |   |   set gamma table
55 *       |   |   |   |   |   |   |   |   |   |   |              |   |   |   |   |   |   |   |   set outline emphasis
56 *       |   |   |   |   |   |   |   |   |   |   |              |   |   |   |   |   |   |   |   |   set dither
57 *       |   |   |   |   |   |   |   |   |   |   |              |   |   |   |   |   |   |   |   |   |   set color correction coefficients
58 *       |   |   |   |   |   |   |   |   |   |   |              |   |   |   |   |   |   |   |   |   |   |   request extension status
59 *       |   |   |   |   |   |   |   |   |   |   |              |   |   |   |   |   |   |   |   |   |   |   |   control an extension
60 *       |   |   |   |   |   |   |   |   |   |   |              |   |   |   |   |   |   |   |   |   |   |   |   |    forward feed / eject
61 *       |   |   |   |   |   |   |   |   |   |   |              |   |   |   |   |   |   |   |   |   |   |   |   |    |   feed
62 *       |   |   |   |   |   |   |   |   |   |   |              |   |   |   |   |   |   |   |   |   |   |   |   |    |   |     request push button status
63 *       |   |   |   |   |   |   |   |   |   |   |              |   |   |   |   |   |   |   |   |   |   |   |   |    |   |     |   control auto area segmentation
64 *       |   |   |   |   |   |   |   |   |   |   |              |   |   |   |   |   |   |   |   |   |   |   |   |    |   |     |   |   set film type
65 *       |   |   |   |   |   |   |   |   |   |   |              |   |   |   |   |   |   |   |   |   |   |   |   |    |   |     |   |   |   set exposure time
66 *       |   |   |   |   |   |   |   |   |   |   |              |   |   |   |   |   |   |   |   |   |   |   |   |    |   |     |   |   |   |   set bay
67 *       |   |   |   |   |   |   |   |   |   |   |              |   |   |   |   |   |   |   |   |   |   |   |   |    |   |     |   |   |   |   |   set threshold
68 *       |   |   |   |   |   |   |   |   |   |   |              |   |   |   |   |   |   |   |   |   |   |   |   |    |   |     |   |   |   |   |   |   set focus position
69 *       |   |   |   |   |   |   |   |   |   |   |              |   |   |   |   |   |   |   |   |   |   |   |   |    |   |     |   |   |   |   |   |   |   request focus position
70 *       |   |   |   |   |   |   |   |   |   |   |              |   |   |   |   |   |   |   |   |   |   |   |   |    |   |     |   |   |   |   |   |   |   |   request extended identity
71 *       |   |   |   |   |   |   |   |   |   |   |              |   |   |   |   |   |   |   |   |   |   |   |   |    |   |     |   |   |   |   |   |   |   |   |   request scanner status
72 *       |   |   |   |   |   |   |   |   |   |   |              |   |   |   |   |   |   |   |   |   |   |   |   |    |   |     |   |   |   |   |   |   |   |   |   |
73 *       |   |   |   |   |   |   |   |   |   |   |              |   |   |   |   |   |   |   |   |   |   |   |   |    |   |     |   |   |   |   |   |   |   |   |   |
74 */
75
76static struct EpsonCmd epson_cmd[] = {
77  {"A1",'I', 0 ,'F','S', 0 ,'G', 0 ,'R', 0 ,'A', 0 ,{ 0, 0, 0}, 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ,  0 , 0   , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 },
78  {"A2",'I', 0 ,'F','S', 0 ,'G','D','R','H','A','L',{-3, 3, 0},'Z','B', 0 ,'@', 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ,  0 , 0   , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 },
79  {"B1",'I', 0 ,'F','S','C','G','D','R', 0 ,'A', 0 ,{ 0, 0, 0}, 0 ,'B', 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ,  0 , 0   , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 },
80  {"B2",'I', 0 ,'F','S','C','G','D','R','H','A','L',{-3, 3, 0},'Z','B', 0 ,'@', 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ,  0 , 0   , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 },
81  {"B3",'I', 0 ,'F','S','C','G','D','R','H','A','L',{-3, 3, 0},'Z','B','M','@', 0 , 0 , 0 , 0 , 0 , 0 ,'m','f','e',  0 , 0   , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 },
82  {"B4",'I', 0 ,'F','S','C','G','D','R','H','A','L',{-3, 3, 0},'Z','B','M','@','g','d', 0 ,'z','Q','b','m','f','e',  0 , 0   , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 },
83  {"B5",'I', 0 ,'F','S','C','G','D','R','H','A','L',{-3, 3, 0},'Z','B','M','@','g','d','K','z','Q','b','m','f','e',  0 , 0   , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 },
84  {"B6",'I', 0 ,'F','S','C','G','D','R','H','A','L',{-3, 3, 0},'Z','B','M','@','g','d','K','z','Q','b','m','f','e',  0 , 0   , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 },
85  {"B7",'I', 0 ,'F','S','C','G','D','R','H','A','L',{-4, 3, 0},'Z','B','M','@','g','d','K','z','Q','b','m','f','e','\f', 0   ,'!','s','N', 0 , 0 ,'t', 0 , 0 ,'I','F'},
86  {"B8",'I', 0 ,'F','S','C','G','D','R','H','A','L',{-4, 3, 0},'Z','B','M','@','g','d','K','z','Q','b','m','f','e','\f', 0x19,'!','s','N', 0 , 0 ,'t','p','q','I','F'},
87/* XXX 'f' probably not supported on F5 */
88  {"F5",'I', 0 ,'F','S','C','G','D','R','H','A','L',{-3, 3, 0},'Z', 0 ,'M','@','g','d','K','z','Q', 0 ,'m','f','e','\f', 0   , 0 , 0 ,'N','T','P', 0 , 0 , 0 , 0 , 0 },
89  {"D1",'I','i','F', 0 ,'C','G','D','R', 0 ,'A', 0 ,{ 0, 0, 0},'Z', 0 , 0 ,'@','g','d', 0 ,'z', 0 , 0 , 0 ,'f', 0 ,  0 , 0   ,'!', 0 , 0 , 0 , 0 ,'t', 0 , 0 , 0 , 0 },
90  {"D2",'I','i','F', 0 ,'C','G','D','R', 0 ,'A', 0 ,{ 0, 0, 0},'Z', 0 , 0 ,'@','g','d', 0 ,'z', 0 , 0 , 0 ,'f','e',  0 , 0   ,'!', 0 ,'N', 0 , 0 ,'t', 0 , 0 , 0 , 0 },
91  {"D7",'I','i','F', 0 ,'C','G','D','R', 0 ,'A', 0 ,{ 0, 0, 0},'Z', 0 , 0 ,'@','g','d', 0 ,'z', 0 , 0 , 0 ,'f','e','\f', 0   ,'!', 0 ,'N', 0 , 0 ,'t', 0 , 0 , 0 , 0 },
92  {"D8",'I','i','F', 0 ,'C','G','D','R', 0 ,'A', 0 ,{ 0, 0, 0},'Z', 0 , 0 ,'@','g','d', 0 ,'z', 0 , 0 , 0 ,'f','e','\f', 0   ,'!', 0 ,'N', 0 , 0 ,'t', 0 , 0 , 0 , 0 },
93};
94
95
96
97extern struct mode_param mode_params[];
98
99/* Define the different scan sources */
100
101#define FBF_STR	SANE_I18N("Flatbed")
102#define TPU_STR	SANE_I18N("Transparency Unit")
103#define TP2_STR SANE_I18N("TPU8x10")
104#define ADF_STR	SANE_I18N("Automatic Document Feeder")
105
106/*
107 * source list need one dummy entry (save device settings is crashing).
108 * NOTE: no const - this list gets created while exploring the capabilities
109 * of the scanner.
110 */
111
112extern SANE_String_Const source_list[];
113
114static int film_params[] = { 0, 1, 2, 3 };
115
116extern const int halftone_params[];
117
118static const int dropout_params[] = {
119	0x00,	/* none */
120	0x10,	/* red */
121	0x20,	/* green */
122	0x30	/* blue */
123};
124
125/*
126 * Color correction:
127 * One array for the actual parameters that get sent to the scanner (color_params[]),
128 * one array for the strings that get displayed in the user interface (correction_list[])
129 * and one array to mark the user defined color correction (correction_userdefined[]).
130 */
131static const int correction_params[] = {
132	0x00,	/* None */
133	0x01,	/* Auto */
134	0x01,	/* User defined */
135};
136
137void
138e2_dev_init(Epson_Device *dev, const char *devname, int conntype)
139{
140	DBG(5, "%s\n", __func__);
141
142	dev->name = NULL;
143	dev->model = NULL;
144	dev->connection = conntype;
145
146	dev->model_id = 0;
147
148	dev->sane.name = devname;
149	dev->sane.model = NULL;
150
151	dev->sane.type = "flatbed scanner";
152	dev->sane.vendor = "Epson";
153
154	dev->optical_res = 0;	/* just to have it initialized */
155	dev->color_shuffle = SANE_FALSE;
156	dev->extension = SANE_FALSE;
157	dev->use_extension = SANE_FALSE;
158
159	dev->need_color_reorder = SANE_FALSE;
160	dev->need_double_vertical = SANE_FALSE;
161
162	dev->cct_profile = &epson_cct_profiles[0]; /* default profile */
163
164	dev->cmd = &epson_cmd[EPSON_LEVEL_DEFAULT];
165
166	/* Change default level when using a network connection */
167	if (dev->connection == SANE_EPSON_NET)
168		dev->cmd = &epson_cmd[EPSON_LEVEL_B7];
169
170	dev->last_res = 0;
171	dev->last_res_preview = 0;	/* set resolution to safe values */
172
173	dev->res_list_size = 0;
174	dev->res_list = NULL;
175}
176
177SANE_Status
178e2_dev_post_init(struct Epson_Device *dev)
179{
180	int i, last;
181
182	DBG(5, "%s\n", __func__);
183
184	/* find cct model id */
185	for (i = 0; epson_cct_models[i].name != NULL; i++) {
186		if (strcmp(epson_cct_models[i].name, dev->model) == 0) {
187			dev->model_id = epson_cct_models[i].id;
188			break;
189		}
190	}
191
192	/* find cct profile */
193	for (i = 0; epson_cct_profiles[i].model != 0xFF; i++) {
194		if (epson_cct_profiles[i].model == dev->model_id) {
195			dev->cct_profile = &epson_cct_profiles[i];
196			break;
197		}
198	}
199
200	DBG(1, "CCT model id is 0x%02x, profile offset %d\n", dev->model_id, i);
201
202	/* If we have been unable to obtain supported resolutions
203	 * due to the fact we are on the network transport,
204	 * add some convenient ones
205	 */
206
207	if (dev->res_list_size == 0) {
208
209		int val = (dev->dpi_range.min < 150) ? 150 : dev->dpi_range.min;
210
211		DBG(1, "cannot obtain resolution list, faking (%d-%d)\n",
212			dev->dpi_range.min, dev->dpi_range.max);
213
214		if (dev->dpi_range.min <= 25)
215			e2_add_resolution(dev, 25);
216
217		if (dev->dpi_range.min <= 50)
218			e2_add_resolution(dev, 50);
219
220		if (dev->dpi_range.min <= 75)
221			e2_add_resolution(dev, 75);
222
223		if (dev->dpi_range.min <= 100)
224			e2_add_resolution(dev, 100);
225
226		while (val <= dev->dpi_range.max) {
227			e2_add_resolution(dev, val);
228			val *= 2;
229		}
230	}
231
232	/* try to expand the resolution list where appropriate */
233
234	last = dev->res_list[dev->res_list_size - 1];
235
236	DBG(1, "highest available resolution: %d\n", last);
237
238	if (dev->optical_res > last) {
239		DBG(1, "adding optical resolution (%d)\n", dev->optical_res);
240		e2_add_resolution(dev, dev->optical_res);
241	}
242
243	/* add missing resolutions for known scanners */
244
245	if (e2_dev_model(dev, "GT-X800") || e2_dev_model(dev, "GT-X700")) {
246
247		DBG(1, "known scanner, integrating resolution list\n");
248		e2_add_resolution(dev, 4800);
249		e2_add_resolution(dev, 6400);
250		e2_add_resolution(dev, 9600);
251		e2_add_resolution(dev, 12800);
252
253		last = dev->res_list[dev->res_list_size - 1];
254	}
255
256	/* guess for the others */
257
258	if (dev->dpi_range.max > last && dev->dpi_range.max != dev->optical_res) {
259
260		int val = last + last;
261
262		DBG(1, "integrating resolution list (%d-%d)\n",
263			val, dev->dpi_range.max);
264
265		while (val <= dev->dpi_range.max) {
266			e2_add_resolution(dev, val);
267			val += last;
268		}
269	}
270
271
272	/*
273	 * Copy the resolution list to the resolution_list array so that the frontend can
274	 * display the correct values
275	 */
276
277	dev->resolution_list =
278		malloc((dev->res_list_size + 1) * sizeof(SANE_Word));
279
280	if (dev->resolution_list == NULL)
281		return SANE_STATUS_NO_MEM;
282
283
284	*(dev->resolution_list) = dev->res_list_size;
285
286	memcpy(&(dev->resolution_list[1]), dev->res_list,
287	       dev->res_list_size * sizeof(SANE_Word));
288
289
290	/* establish defaults */
291	dev->need_reset_on_source_change = SANE_FALSE;
292
293	if (e2_dev_model(dev, "ES-9000H") || e2_dev_model(dev, "GT-30000")) {
294		dev->focusSupport = SANE_FALSE;
295		dev->cmd->feed = 0x19;
296	}
297
298	if (e2_dev_model(dev, "GT-8200") || e2_dev_model(dev, "Perfection1650")
299	    || e2_dev_model(dev, "Perfection1640") || e2_dev_model(dev, "GT-8700")) {
300		dev->focusSupport = SANE_FALSE;
301		dev->cmd->feed = 0;
302		dev->need_reset_on_source_change = SANE_TRUE;
303	}
304
305	if (e2_dev_model(dev, "DS-G20000"))
306		dev->cmd->bright_range.min = -3;
307
308	return SANE_STATUS_GOOD;
309}
310
311
312SANE_Bool
313e2_dev_model(Epson_Device *dev, const char *model)
314{
315	if (dev->model == NULL)
316		return SANE_FALSE;
317
318	if (strncmp(dev->model, model, strlen(model)) == 0)
319		return SANE_TRUE;
320
321	return SANE_FALSE;
322}
323
324void
325e2_set_cmd_level(SANE_Handle handle, unsigned char *level)
326{
327	Epson_Scanner *s = (Epson_Scanner *) handle;
328	Epson_Device *dev = s->hw;
329
330	int n;
331
332	DBG(1, "%s: %c%c\n", __func__, level[0], level[1]);
333
334	/* set command type and level */
335	for (n = 0; n < NELEMS(epson_cmd); n++) {
336		char type_level[3];
337		sprintf(type_level, "%c%c", level[0], level[1]);
338		if (!strncmp(type_level, epson_cmd[n].level, 2))
339			break;
340	}
341
342	if (n < NELEMS(epson_cmd)) {
343		dev->cmd = &epson_cmd[n];
344	} else {
345		dev->cmd = &epson_cmd[EPSON_LEVEL_DEFAULT];
346		DBG(1, " unknown type %c or level %c, using %s\n",
347		    level[0], level[1], dev->cmd->level);
348	}
349
350	s->hw->level = dev->cmd->level[1] - '0';
351}
352
353SANE_Status
354e2_set_model(Epson_Scanner * s, unsigned char *model, size_t len)
355{
356	unsigned char *buf;
357	unsigned char *p;
358	struct Epson_Device *dev = s->hw;
359
360	buf = malloc(len + 1);
361	if (buf == NULL)
362		return SANE_STATUS_NO_MEM;
363
364	memcpy(buf, model, len);
365	buf[len] = '\0';
366
367	p = &buf[len - 1];
368
369	while (*p == ' ') {
370		*p = '\0';
371		p--;
372	}
373
374	if (dev->model)
375		free(dev->model);
376
377	dev->model = strndup((const char *) buf, len);
378	dev->sane.model = dev->model;
379
380	DBG(10, "%s: model is '%s'\n", __func__, dev->model);
381
382	free(buf);
383
384	return SANE_STATUS_GOOD;
385}
386
387SANE_Status
388e2_add_resolution(Epson_Device *dev, int r)
389{
390	dev->res_list_size++;
391	dev->res_list = (SANE_Int *) realloc(dev->res_list,
392					     dev->res_list_size *
393					     sizeof(SANE_Word));
394
395	DBG(10, "%s: add (dpi): %d\n", __func__, r);
396
397	if (dev->res_list == NULL)
398		return SANE_STATUS_NO_MEM;
399
400	dev->res_list[dev->res_list_size - 1] = (SANE_Int) r;
401
402	return SANE_STATUS_GOOD;
403}
404
405void
406e2_set_fbf_area(Epson_Scanner * s, int x, int y, int unit)
407{
408	struct Epson_Device *dev = s->hw;
409
410	if (x == 0 || y == 0)
411		return;
412
413	dev->fbf_x_range.min = 0;
414	dev->fbf_x_range.max = SANE_FIX(x * MM_PER_INCH / unit);
415	dev->fbf_x_range.quant = 0;
416
417	dev->fbf_y_range.min = 0;
418	dev->fbf_y_range.max = SANE_FIX(y * MM_PER_INCH / unit);
419	dev->fbf_y_range.quant = 0;
420
421	DBG(5, "%s: %f,%f %f,%f %d [mm]\n",
422	    __func__,
423	    SANE_UNFIX(dev->fbf_x_range.min),
424	    SANE_UNFIX(dev->fbf_y_range.min),
425	    SANE_UNFIX(dev->fbf_x_range.max),
426	    SANE_UNFIX(dev->fbf_y_range.max), unit);
427}
428
429void
430e2_set_adf_area(struct Epson_Scanner *s, int x, int y, int unit)
431{
432	struct Epson_Device *dev = s->hw;
433
434	dev->adf_x_range.min = 0;
435	dev->adf_x_range.max = SANE_FIX(x * MM_PER_INCH / unit);
436	dev->adf_x_range.quant = 0;
437
438	dev->adf_y_range.min = 0;
439	dev->adf_y_range.max = SANE_FIX(y * MM_PER_INCH / unit);
440	dev->adf_y_range.quant = 0;
441
442	DBG(5, "%s: %f,%f %f,%f %d [mm]\n",
443	    __func__,
444	    SANE_UNFIX(dev->adf_x_range.min),
445	    SANE_UNFIX(dev->adf_y_range.min),
446	    SANE_UNFIX(dev->adf_x_range.max),
447	    SANE_UNFIX(dev->adf_y_range.max), unit);
448}
449
450void
451e2_set_tpu_area(struct Epson_Scanner *s, int x, int y, int unit)
452{
453	struct Epson_Device *dev = s->hw;
454
455	dev->tpu_x_range.min = 0;
456	dev->tpu_x_range.max = SANE_FIX(x * MM_PER_INCH / unit);
457	dev->tpu_x_range.quant = 0;
458
459	dev->tpu_y_range.min = 0;
460	dev->tpu_y_range.max = SANE_FIX(y * MM_PER_INCH / unit);
461	dev->tpu_y_range.quant = 0;
462
463	DBG(5, "%s: %f,%f %f,%f %d [mm]\n",
464	    __func__,
465	    SANE_UNFIX(dev->tpu_x_range.min),
466	    SANE_UNFIX(dev->tpu_y_range.min),
467	    SANE_UNFIX(dev->tpu_x_range.max),
468	    SANE_UNFIX(dev->tpu_y_range.max), unit);
469}
470
471void
472e2_set_tpu2_area(struct Epson_Scanner *s, int x, int y, int unit)
473{
474	struct Epson_Device *dev = s->hw;
475
476	dev->tpu2_x_range.min = 0;
477	dev->tpu2_x_range.max = SANE_FIX(x * MM_PER_INCH / unit);
478	dev->tpu2_x_range.quant = 0;
479
480	dev->tpu2_y_range.min = 0;
481	dev->tpu2_y_range.max = SANE_FIX(y * MM_PER_INCH / unit);
482	dev->tpu2_y_range.quant = 0;
483
484	DBG(5, "%s: %f,%f %f,%f %d [mm]\n",
485	    __func__,
486	    SANE_UNFIX(dev->tpu2_x_range.min),
487	    SANE_UNFIX(dev->tpu2_y_range.min),
488	    SANE_UNFIX(dev->tpu2_x_range.max),
489	    SANE_UNFIX(dev->tpu2_y_range.max), unit);
490}
491
492void
493e2_add_depth(Epson_Device *dev, SANE_Int depth)
494{
495	DBG(10, "%s: add (bpp): %d\n", __func__, depth);
496
497	if (depth > dev->maxDepth)
498		dev->maxDepth = depth;
499
500	dev->depth_list[0]++;
501	dev->depth_list[dev->depth_list[0]] = depth;
502}
503
504/* A little helper function to correct the extended status reply
505 * gotten from scanners with known buggy firmware.
506 */
507static void
508fix_up_extended_status_reply(Epson_Scanner * s, unsigned char *buf)
509{
510	if (e2_model(s, "ES-9000H") || e2_model(s, "GT-30000")) {
511		DBG(1, "fixing up buggy ADF max scan dimensions.\n");
512		buf[2] = 0xB0;
513		buf[3] = 0x6D;
514		buf[4] = 0x60;
515		buf[5] = 0x9F;
516	}
517}
518
519
520SANE_Status
521e2_discover_capabilities(Epson_Scanner *s)
522{
523	SANE_Status status;
524
525	unsigned char scanner_status;
526	Epson_Device *dev = s->hw;
527
528	SANE_String_Const *source_list_add = source_list;
529
530	DBG(5, "%s\n", __func__);
531
532	/* always add flatbed */
533	*source_list_add++ = FBF_STR;
534
535	/* ESC I, request identity
536	 * this must be the first command on the FilmScan 200
537	 */
538	if (dev->connection != SANE_EPSON_NET) {
539		unsigned int n, k, x = 0, y = 0;
540		unsigned char *buf, *area;
541		size_t len;
542
543		status = esci_request_identity(s, &buf, &len);
544		if (status != SANE_STATUS_GOOD)
545			return status;
546
547		e2_set_cmd_level(s, &buf[0]);
548
549		/* Setting available resolutions and xy ranges for sane frontend. */
550		/* cycle thru the resolutions, saving them in a list */
551		for (n = 2, k = 0; n < len; n += k) {
552
553			area = buf + n;
554
555			switch (*area) {
556			case 'R':
557			{
558				int val = area[2] << 8 | area[1];
559
560				status = e2_add_resolution(s->hw, val);
561				k = 3;
562				continue;
563			}
564			case 'A':
565			{
566				x = area[2] << 8 | area[1];
567				y = area[4] << 8 | area[3];
568
569				DBG(1, "maximum scan area: %dx%d\n", x, y);
570				k = 5;
571				continue;
572			}
573			default:
574				break;
575			}
576		}
577
578		/* min and max dpi */
579		dev->dpi_range.min = dev->res_list[0];
580		dev->dpi_range.max = dev->res_list[dev->res_list_size - 1];
581		dev->dpi_range.quant = 0;
582
583		e2_set_fbf_area(s, x, y, dev->dpi_range.max);
584
585		free(buf);
586	}
587
588	/* ESC F, request status */
589	status = esci_request_status(s, &scanner_status);
590	if (status != SANE_STATUS_GOOD)
591		return status;
592
593	/* set capabilities */
594	if (scanner_status & STATUS_OPTION)
595		dev->extension = SANE_TRUE;
596
597	if (scanner_status & STATUS_EXT_COMMANDS)
598		dev->extended_commands = 1;
599
600	/*
601	 * Extended status flag request (ESC f).
602	 * this also requests the scanner device name from the scanner.
603	 * It seems unsupported on the network transport (CX11NF/LP-A500).
604	 */
605
606	if (dev->cmd->request_extended_status && dev->connection != SANE_EPSON_NET) {
607
608		unsigned char *es;
609		size_t es_len;
610
611		DBG(1, "detection with request_extended_status\n");
612
613		status = esci_request_extended_status(s, &es, &es_len);
614		if (status != SANE_STATUS_GOOD)
615			return status;
616
617		/*
618		 * Get the device name and copy it to dev->sane.model.
619		 * The device name starts at es[0x1A] and is up to 16 bytes long
620		 * We are overwriting whatever was set previously!
621		 */
622		if (es_len == CMD_SIZE_EXT_STATUS)	/* 42 */
623			e2_set_model(s, es + 0x1A, 16);
624
625		if (es[0] & EXT_STATUS_LID)
626			DBG(1, "LID detected\n");
627
628		if (es[0] & EXT_STATUS_PB)
629			DBG(1, "push button detected\n");
630		else
631			dev->cmd->request_push_button_status = 0;
632
633		/* Flatbed */
634		e2_set_fbf_area(s, es[13] << 8 | es[12], es[15] << 8 | es[14],
635				dev->dpi_range.max);
636
637		/* ADF */
638		if (dev->extension && (es[1] & EXT_STATUS_IST)) {
639			DBG(1, "ADF detected\n");
640
641			fix_up_extended_status_reply(s, es);
642
643			dev->duplex = (es[0] & EXT_STATUS_ADFS) != 0;
644			if (dev->duplex)
645				DBG(1, "ADF supports duplex\n");
646
647			if (es[1] & EXT_STATUS_EN) {
648				DBG(1, "ADF is enabled\n");
649				dev->x_range = &dev->adf_x_range;
650				dev->y_range = &dev->adf_y_range;
651			}
652
653			e2_set_adf_area(s, es[3] << 8 | es[2],
654					es[5] << 8 | es[4],
655					dev->dpi_range.max);
656			*source_list_add++ = ADF_STR;
657
658			dev->ADF = SANE_TRUE;
659		}
660
661		/* TPU */
662		if (dev->extension && (es[6] & EXT_STATUS_IST)) {
663			DBG(1, "TPU detected\n");
664
665			if (es[6] & EXT_STATUS_EN) {
666				DBG(1, "TPU is enabled\n");
667				dev->x_range = &dev->tpu_x_range;
668				dev->y_range = &dev->tpu_y_range;
669			}
670
671			e2_set_tpu_area(s,
672					(es[8] << 8 | es[7]),
673					(es[10] << 8 | es[9]),
674					dev->dpi_range.max);
675
676			*source_list_add++ = TPU_STR;
677			dev->TPU = SANE_TRUE;
678		}
679
680		free(es);
681
682		*source_list_add = NULL; /* add end marker to source list */
683	}
684
685	/* FS I, request extended identity (B7/B8) */
686	if (dev->extended_commands && dev->cmd->request_extended_identity) {
687		unsigned char buf[80];
688
689		DBG(1, "detection with request_extended_identity\n");
690
691		status = esci_request_extended_identity(s, buf);
692		if (status != SANE_STATUS_GOOD)
693			return status;
694
695		e2_set_cmd_level(s, &buf[0]);
696
697		dev->maxDepth = buf[67];
698
699		/* set model name. it will probably be
700		 * different than the one reported by request_identity
701		 * for the same unit (i.e. LP-A500 vs CX11) .
702		 */
703		e2_set_model(s, &buf[46], 16);
704
705		dev->optical_res = le32atoh(&buf[4]);
706
707		dev->dpi_range.min = le32atoh(&buf[8]);
708		dev->dpi_range.max = le32atoh(&buf[12]);
709
710		/* Flatbed */
711		e2_set_fbf_area(s, le32atoh(&buf[20]),
712				le32atoh(&buf[24]), dev->optical_res);
713
714		/* ADF */
715		if (le32atoh(&buf[28]) > 0) {
716			e2_set_adf_area(s, le32atoh(&buf[28]),
717					le32atoh(&buf[32]), dev->optical_res);
718
719			if (!dev->ADF) {
720				*source_list_add++ = ADF_STR;
721				dev->ADF = SANE_TRUE;
722			}
723
724			if (buf[44] & EXT_IDTY_CAP1_ADFS) {
725				dev->duplex = SANE_TRUE;
726			}
727
728		}
729
730		/* TPU */
731		if (le32atoh(&buf[36]) > 0 && !dev->TPU) {
732			e2_set_tpu_area(s,
733					le32atoh(&buf[36]),
734					le32atoh(&buf[40]), dev->optical_res);
735
736			*source_list_add++ = TPU_STR;
737			dev->TPU = SANE_TRUE;
738		}
739
740                /* TPU2 */
741		if (e2_model(s, "GT-X800") || e2_model(s, "GT-X900") || e2_model(s, "GT-X980")) {
742			if (le32atoh(&buf[68]) > 0 ) {
743				e2_set_tpu2_area(s,
744					  	 le32atoh(&buf[68]),
745						 le32atoh(&buf[72]),
746						 dev->optical_res);
747
748				*source_list_add++ = TP2_STR;
749			}
750		}
751
752		*source_list_add = NULL; /* add end marker to source list */
753
754	} else {
755		DBG(1, "no command available to detect capabilities\n");
756	}
757
758	/*
759	 * request identity 2 (ESC i), if available will
760	 * get the information from the scanner and store it in dev
761	 */
762
763	if (dev->cmd->request_identity2 && dev->connection != SANE_EPSON_NET) {
764		unsigned char *buf;
765		status = esci_request_identity2(s, &buf);
766		if (status != SANE_STATUS_GOOD)
767			return status;
768
769		/* the first two bytes of the buffer contain the optical resolution */
770		dev->optical_res = buf[1] << 8 | buf[0];
771
772		/*
773		 * the 4th and 5th byte contain the line distance. Both values have to
774		 * be identical, otherwise this software can not handle this scanner.
775		 */
776		if (buf[4] != buf[5]) {
777			status = SANE_STATUS_INVAL;
778			return status;
779		}
780
781		dev->max_line_distance = buf[4];
782	}
783
784	/*
785	 * Check for the max. supported color depth and assign
786	 * the values to the bitDepthList.
787	 */
788	dev->depth_list = malloc(sizeof(SANE_Int) * (4 + 1));
789	if (dev->depth_list == NULL) {
790		DBG(1, "out of memory (line %d)\n", __LINE__);
791		return SANE_STATUS_NO_MEM;
792	}
793
794	dev->depth_list[0] = 0;
795
796	/* maximum depth discovery */
797	DBG(3, "discovering max depth, NAKs are expected\n");
798
799	/* add default depth */
800	e2_add_depth(dev, 8);
801
802	if (dev->maxDepth >= 12 || dev->maxDepth == 0) {
803		if (esci_set_data_format(s, 12) == SANE_STATUS_GOOD)
804			e2_add_depth(dev, 12);
805	}
806
807	if (dev->maxDepth >= 14 || dev->maxDepth == 0) {
808		if (esci_set_data_format(s, 14) == SANE_STATUS_GOOD)
809			e2_add_depth(dev, 14);
810	}
811
812	if (dev->maxDepth >= 16 || dev->maxDepth == 0) {
813		if (esci_set_data_format(s, 16) == SANE_STATUS_GOOD)
814			e2_add_depth(dev, 16);
815	}
816
817	DBG(1, "maximum supported color depth: %d\n", dev->maxDepth);
818
819	/*
820	 * We assume that setting focus is supported when we can get the focus.
821	 * This assumption may be overridden in e2_dev_post_init()
822	 */
823	if (esci_request_focus_position(s, &s->currentFocusPosition) ==
824	    SANE_STATUS_GOOD) {
825		DBG(1, "getting focus is supported, current focus: %u\n", s->currentFocusPosition);
826		dev->focusSupport = SANE_TRUE;
827		s->opt[OPT_FOCUS_POS].cap &= ~SANE_CAP_INACTIVE;
828		s->val[OPT_FOCUS_POS].w = s->currentFocusPosition;
829	} else {
830		DBG(1, "getting focus is not supported\n");
831		dev->focusSupport = SANE_FALSE;
832		s->opt[OPT_FOCUS_POS].cap |= SANE_CAP_INACTIVE;
833		s->val[OPT_FOCUS_POS].w = FOCUS_ON_GLASS;	/* just in case */
834	}
835
836	/* Set defaults for no extension. */
837	dev->x_range = &dev->fbf_x_range;
838	dev->y_range = &dev->fbf_y_range;
839
840	/*
841	 * Correct for a firmware bug in some Perfection 1650 scanners:
842	 * Firmware version 1.08 reports only half the vertical scan area, we have
843	 * to double the number. To find out if we have to do this, we just compare
844	 * is the vertical range is smaller than the horizontal range.
845	 */
846
847	if ((dev->x_range->max - dev->x_range->min) >
848	    (dev->y_range->max - dev->y_range->min)) {
849		DBG(1, "found buggy scan area, doubling it.\n");
850		dev->y_range->max += (dev->y_range->max - dev->y_range->min);
851		dev->need_double_vertical = SANE_TRUE;
852		dev->need_color_reorder = SANE_TRUE;
853	}
854
855	/* FS F, request scanner status */
856	if (dev->extended_commands) {
857		unsigned char buf[16];
858
859		status = esci_request_scanner_status(s, buf);
860		if (status != SANE_STATUS_GOOD)
861			return status;
862	}
863
864	return status;
865}
866
867
868SANE_Status
869e2_set_extended_scanning_parameters(Epson_Scanner * s)
870{
871	unsigned char buf[64];
872
873	const struct mode_param *mparam;
874
875	DBG(1, "%s\n", __func__);
876
877	mparam = &mode_params[s->val[OPT_MODE].w];
878
879	memset(buf, 0x00, sizeof(buf));
880
881	/* ESC R, resolution */
882	htole32a(&buf[0], s->val[OPT_RESOLUTION].w);
883	htole32a(&buf[4], s->val[OPT_RESOLUTION].w);
884
885	/* ESC A, scanning area */
886	htole32a(&buf[8], s->left);
887	htole32a(&buf[12], s->top);
888	htole32a(&buf[16], s->params.pixels_per_line);
889	htole32a(&buf[20], s->params.lines);
890
891	/*
892	 * The byte sequence mode was introduced in B5,
893	 *for B[34] we need line sequence mode
894	 */
895
896	/* ESC C, set color */
897	if ((s->hw->cmd->level[0] == 'D'
898	     || (s->hw->cmd->level[0] == 'B' && s->hw->level >= 5))
899	    && mparam->flags == 0x02) {
900		buf[24] = 0x13;
901	} else {
902		buf[24] = mparam->flags | (mparam->dropout_mask
903					   & dropout_params[s->
904							    val[OPT_DROPOUT].
905							    w]);
906	}
907
908	/* ESC D, set data format */
909	mparam = &mode_params[s->val[OPT_MODE].w];
910	buf[25] = mparam->depth;
911
912	/* ESC e, control option */
913	if (s->hw->extension) {
914
915		char extensionCtrl;
916		extensionCtrl = (s->hw->use_extension ? 1 : 0);
917		if (s->hw->use_extension && (s->val[OPT_ADF_MODE].w == 1)) {
918			extensionCtrl = 2;
919		}
920
921		/* Test for TPU2
922		 * Epson Perfection 4990 Command Specifications
923		 * JZIS-0075 Rev. A, page 31
924		 */
925		if (s->hw->use_extension && s->hw->TPU2) {
926			extensionCtrl = 5;
927		}
928
929		if (s->val[OPT_MODE].w == MODE_INFRARED) {
930                        /* only infrared in TPU mode (NOT in TPU2 or flatbeth)
931	                 * XXX investigate this ... only tested on GT-X800
932                         */
933
934                        if (extensionCtrl == 1)   /* test for TPU */
935				extensionCtrl = 3;
936                        else
937				return SANE_STATUS_UNSUPPORTED;
938		}
939
940		/* ESC e */
941		buf[26] = extensionCtrl;
942	}
943
944	/* ESC g, scanning mode (normal or high speed) */
945	if (s->val[OPT_PREVIEW].w)
946		buf[27] = 1;	/* High speed */
947	else
948		buf[27] = 0;
949
950	/* ESC d, block line number */
951	buf[28] = s->lcount;
952
953	/* ESC Z, set gamma correction */
954	buf[29] = 0x01;		/* default */
955
956	if (SANE_OPTION_IS_ACTIVE(s->opt[OPT_GAMMA_CORRECTION].cap)) {
957		char val;
958		if (s->hw->cmd->level[0] == 'D') {
959			/* The D1 level has only the two user defined gamma
960			 * settings.
961			 */
962			val = gamma_params[s->val[OPT_GAMMA_CORRECTION].w];
963		} else {
964			val = gamma_params[s->val[OPT_GAMMA_CORRECTION].w];
965
966			/*
967			 * If "Default" is selected then determine the actual value
968			 * to send to the scanner: If bilevel mode, just send the
969			 * value from the table (0x01), for grayscale or color mode
970			 * add one and send 0x02.
971			 */
972
973			if (s->val[OPT_GAMMA_CORRECTION].w == 0) {
974				val += mparam->depth == 1 ? 0 : 1;
975			}
976		}
977
978		buf[29] = val;
979	}
980
981	/* ESC L, set brightness */
982	if (SANE_OPTION_IS_ACTIVE(s->opt[OPT_BRIGHTNESS].cap))
983		buf[30] = s->val[OPT_BRIGHTNESS].w;
984
985	/* ESC B, set halftoning mode / halftone processing */
986	if (SANE_OPTION_IS_ACTIVE(s->opt[OPT_HALFTONE].cap))
987		buf[32] = halftone_params[s->val[OPT_HALFTONE].w];
988
989	/* ESC s, auto area segmentation */
990	if (SANE_OPTION_IS_ACTIVE(s->opt[OPT_AAS].cap))
991		buf[34] = s->val[OPT_AAS].w;
992
993	/* ESC Q, set sharpness / sharpness control */
994	if (SANE_OPTION_IS_ACTIVE(s->opt[OPT_SHARPNESS].cap))
995		buf[35] = s->val[OPT_SHARPNESS].w;
996
997	/* ESC K, set data order / mirroring */
998	if (SANE_OPTION_IS_ACTIVE(s->opt[OPT_MIRROR].cap))
999		buf[36] = s->val[OPT_MIRROR].w;
1000
1001	/* ESC N, film type */
1002	if (SANE_OPTION_IS_ACTIVE(s->opt[OPT_FILM_TYPE].cap))
1003		buf[37] = film_params[s->val[OPT_FILM_TYPE].w];
1004
1005	/* ESC M, color correction */
1006	buf[31] = correction_params[s->val[OPT_COLOR_CORRECTION].w];
1007
1008	/* ESC t, threshold */
1009	buf[33] = s->val[OPT_THRESHOLD].w;
1010
1011	return esci_set_scanning_parameter(s, buf);
1012}
1013
1014SANE_Status
1015e2_set_scanning_parameters(Epson_Scanner * s)
1016{
1017	SANE_Status status;
1018	struct mode_param *mparam = &mode_params[s->val[OPT_MODE].w];
1019	unsigned char color_mode;
1020
1021	DBG(1, "%s\n", __func__);
1022
1023	/*
1024	 *  There is some undocumented special behavior with the TPU enable/disable.
1025	 *      TPU power  ESC e      status
1026	 *      on           0        NAK
1027	 *      on           1        ACK
1028	 *      off          0        ACK
1029	 *      off          1        NAK
1030	 *
1031	 * It makes no sense to scan with TPU powered on and source flatbed, because
1032	 * light will come from both sides.
1033	 */
1034
1035	if (s->hw->extension) {
1036
1037		int extensionCtrl;
1038		extensionCtrl = (s->hw->use_extension ? 1 : 0);
1039		if (s->hw->use_extension && (s->val[OPT_ADF_MODE].w == 1))
1040			extensionCtrl = 2;
1041
1042		status = esci_control_extension(s, extensionCtrl);
1043		if (status != SANE_STATUS_GOOD) {
1044			DBG(1, "you may have to power %s your TPU\n",
1045			    s->hw->use_extension ? "on" : "off");
1046			DBG(1,
1047			    "and you may also have to restart the SANE frontend.\n");
1048			return status;
1049		}
1050
1051		/* XXX use request_extended_status and analyze
1052		 * buffer to set the scan area for
1053		 * ES-9000H and GT-30000
1054		 */
1055	}
1056
1057	/* ESC C, Set color */
1058	color_mode = mparam->flags | (mparam->dropout_mask
1059				      & dropout_params[s->val[OPT_DROPOUT].
1060						       w]);
1061
1062	/*
1063	 * The byte sequence mode was introduced in B5, for B[34] we need line sequence mode
1064	 * XXX Check what to do for the FilmScan 200
1065	 */
1066	if ((s->hw->cmd->level[0] == 'D'
1067	     || (s->hw->cmd->level[0] == 'B' && s->hw->level >= 5))
1068	    && mparam->flags == 0x02)
1069		color_mode = 0x13;
1070
1071	status = esci_set_color_mode(s, color_mode);
1072	if (status != SANE_STATUS_GOOD)
1073		return status;
1074
1075	/* ESC D, set data format */
1076	DBG(1, "%s: setting data format to %d bits\n", __func__,
1077	    mparam->depth);
1078	status = esci_set_data_format(s, mparam->depth);
1079	if (status != SANE_STATUS_GOOD)
1080		return status;
1081
1082	/* ESC B, set halftoning mode */
1083	if (s->hw->cmd->set_halftoning
1084	    && SANE_OPTION_IS_ACTIVE(s->opt[OPT_HALFTONE].cap)) {
1085		status = esci_set_halftoning(s,
1086					     halftone_params[s->
1087							     val
1088							     [OPT_HALFTONE].
1089							     w]);
1090		if (status != SANE_STATUS_GOOD)
1091			return status;
1092	}
1093
1094	/* ESC L, set brightness */
1095	if (SANE_OPTION_IS_ACTIVE(s->opt[OPT_BRIGHTNESS].cap)) {
1096		status = esci_set_bright(s, s->val[OPT_BRIGHTNESS].w);
1097		if (status != SANE_STATUS_GOOD)
1098			return status;
1099	}
1100
1101	if (SANE_OPTION_IS_ACTIVE(s->opt[OPT_AAS].cap)) {
1102		status = esci_set_auto_area_segmentation(s,
1103							 s->val[OPT_AAS].w);
1104		if (status != SANE_STATUS_GOOD)
1105			return status;
1106	}
1107
1108	if (SANE_OPTION_IS_ACTIVE(s->opt[OPT_FILM_TYPE].cap)) {
1109		status = esci_set_film_type(s,
1110					film_params[s->val[OPT_FILM_TYPE].w]);
1111
1112		if (status != SANE_STATUS_GOOD)
1113			return status;
1114	}
1115
1116	if (s->hw->cmd->set_gamma
1117	    && SANE_OPTION_IS_ACTIVE(s->opt[OPT_GAMMA_CORRECTION].cap)) {
1118		int val;
1119		if (s->hw->cmd->level[0] == 'D') {
1120			/*
1121			 * The D1 level has only the two user defined gamma
1122			 * settings.
1123			 */
1124			val = gamma_params[s->val[OPT_GAMMA_CORRECTION].w];
1125		} else {
1126			val = gamma_params[s->val[OPT_GAMMA_CORRECTION].w];
1127
1128			/*
1129			 * If "Default" is selected then determine the actual value
1130			 * to send to the scanner: If bilevel mode, just send the
1131			 * value from the table (0x01), for grayscale or color mode
1132			 * add one and send 0x02.
1133			 */
1134
1135/*			if( s->val[ OPT_GAMMA_CORRECTION].w <= 1) { */
1136			if (s->val[OPT_GAMMA_CORRECTION].w == 0) {
1137				val += mparam->depth == 1 ? 0 : 1;
1138			}
1139		}
1140
1141		status = esci_set_gamma(s, val);
1142		if (status != SANE_STATUS_GOOD)
1143			return status;
1144	}
1145
1146	if (s->hw->cmd->set_threshold != 0
1147	    && SANE_OPTION_IS_ACTIVE(s->opt[OPT_THRESHOLD].cap)) {
1148		status = esci_set_threshold(s, s->val[OPT_THRESHOLD].w);
1149		if (status != SANE_STATUS_GOOD)
1150			return status;
1151	}
1152
1153	/* XXX ESC Z here */
1154
1155	/* ESC M, set color correction */
1156	if (SANE_OPTION_IS_ACTIVE(s->opt[OPT_COLOR_CORRECTION].cap)) {
1157
1158		status = esci_set_color_correction(s,
1159			correction_params[s->val[OPT_COLOR_CORRECTION].w]);
1160
1161		if (status != SANE_STATUS_GOOD)
1162			return status;
1163	}
1164
1165	/* ESC Q, set sharpness */
1166	if (SANE_OPTION_IS_ACTIVE(s->opt[OPT_SHARPNESS].cap)) {
1167
1168		status = esci_set_sharpness(s, s->val[OPT_SHARPNESS].w);
1169		if (status != SANE_STATUS_GOOD)
1170			return status;
1171	}
1172
1173	/* ESC g, set scanning mode */
1174	if (s->val[OPT_PREVIEW].w)
1175		status = esci_set_speed(s, 1);
1176	else
1177		status = esci_set_speed(s, 0);
1178
1179	if (status != SANE_STATUS_GOOD)
1180		return status;
1181
1182	/* ESC K, set data order */
1183	if (SANE_OPTION_IS_ACTIVE(s->opt[OPT_MIRROR].cap)) {
1184		status = esci_mirror_image(s, s->val[OPT_MIRROR].w);
1185		if (status != SANE_STATUS_GOOD)
1186			return status;
1187	}
1188
1189	/* ESC R */
1190	status = esci_set_resolution(s, s->val[OPT_RESOLUTION].w,
1191				     s->val[OPT_RESOLUTION].w);
1192	if (status != SANE_STATUS_GOOD)
1193		return status;
1194
1195	/* ESC H, set zoom */
1196	/* not implemented */
1197
1198	/* ESC A, set scanning area */
1199
1200	/*
1201	 * Modify the scan area: If the scanner requires color shuffling, then we try to
1202	 * scan more lines to compensate for the lines that will be removed from the scan
1203	 * due to the color shuffling algorithm.
1204	 */
1205
1206	if (s->hw->color_shuffle == SANE_TRUE) {
1207
1208		unsigned int lines = s->params.lines + (2 * s->line_distance);
1209		int top = s->top - (1 * s->line_distance);
1210
1211		if (top < 0)
1212			top = 0;
1213
1214		status = esci_set_scan_area(s, s->left, top,
1215				    s->params.pixels_per_line,
1216				    lines);
1217
1218	} else {
1219
1220		status = esci_set_scan_area(s, s->left, s->top,
1221				    s->params.pixels_per_line,
1222				    s->params.lines);
1223	}
1224
1225	if (status != SANE_STATUS_GOOD)
1226		return status;
1227
1228	/* ESC d, set block line number / set line counter */
1229	status = esci_set_lcount(s, s->lcount);
1230	if (status != SANE_STATUS_GOOD)
1231		return status;
1232
1233	return SANE_STATUS_GOOD;
1234}
1235
1236void
1237e2_setup_block_mode(Epson_Scanner * s)
1238{
1239	int maxreq;
1240
1241	DBG(5, "%s\n", __func__);
1242
1243	s->block = SANE_TRUE;
1244
1245	if (s->hw->connection == SANE_EPSON_SCSI)
1246		maxreq = sanei_scsi_max_request_size;
1247	else if (s->hw->connection == SANE_EPSON_USB)
1248		maxreq = 128 * 1024;
1249	else
1250		maxreq = 32 * 1024;
1251
1252	/* XXX verify if this can b extended to other models */
1253	if (s->hw->connection == SANE_EPSON_NET && e2_model(s, "LP-A500"))
1254		maxreq = 64 * 1024;
1255
1256	s->lcount = maxreq / s->params.bytes_per_line;
1257
1258	DBG(1, "max req size: %d, line count: %d\n", maxreq, s->lcount);
1259
1260	/* XXX investigate this */
1261	if (s->lcount < 3 && (e2_model(s, "GT-X800") || e2_model(s, "GT-X900") || e2_model(s, "GT-X980"))) {
1262		s->lcount = 21;
1263		DBG(17,
1264		    "%s: set lcount = %i bigger than sanei_scsi_max_request_size\n",
1265		    __func__, s->lcount);
1266	}
1267
1268	if (s->lcount >= 255)
1269		s->lcount = 255;
1270
1271	/* XXX why this? */
1272	if (s->hw->TPU && s->hw->use_extension && s->lcount > 32)
1273		s->lcount = 32;
1274
1275	/*
1276	 * The D1 series of scanners only allow an even line number
1277	 * for bi-level scanning. If a bit depth of 1 is selected, then
1278	 * make sure the next lower even number is selected.
1279	 */
1280
1281	/* XXX check bith depth? */
1282	if (s->hw->cmd->level[0] == 'D' && s->lcount > 3 && s->lcount % 2)
1283		s->lcount -= 1;
1284
1285	DBG(1, "final line count is %d\n", s->lcount);
1286}
1287
1288SANE_Status
1289e2_init_parameters(Epson_Scanner * s)
1290{
1291	int dpi, bytes_per_pixel;
1292	struct mode_param *mparam;
1293
1294	DBG(5, "%s\n", __func__);
1295
1296	memset(&s->params, 0, sizeof(SANE_Parameters));
1297
1298	dpi = s->val[OPT_RESOLUTION].w;
1299
1300	mparam = &mode_params[s->val[OPT_MODE].w];
1301
1302	if (SANE_UNFIX(s->val[OPT_BR_Y].w) == 0 ||
1303		SANE_UNFIX(s->val[OPT_BR_X].w) == 0)
1304		return SANE_STATUS_INVAL;
1305
1306	s->left = ((SANE_UNFIX(s->val[OPT_TL_X].w) / MM_PER_INCH) *
1307		s->val[OPT_RESOLUTION].w) + 0.5;
1308
1309	s->top = ((SANE_UNFIX(s->val[OPT_TL_Y].w) / MM_PER_INCH) *
1310		s->val[OPT_RESOLUTION].w) + 0.5;
1311
1312	s->params.pixels_per_line =
1313		((SANE_UNFIX(s->val[OPT_BR_X].w -
1314			   s->val[OPT_TL_X].w) / MM_PER_INCH) * dpi) + 0.5;
1315	s->params.lines =
1316		((SANE_UNFIX(s->val[OPT_BR_Y].w -
1317			   s->val[OPT_TL_Y].w) / MM_PER_INCH) * dpi) + 0.5;
1318
1319
1320	DBG(1, "%s: resolution = %d, preview = %d\n",
1321		__func__, s->val[OPT_RESOLUTION].w, s->val[OPT_PREVIEW].w);
1322
1323	DBG(1, "%s: %p %p tlx %f tly %f brx %f bry %f [mm]\n",
1324	    __func__, (void *) s, (void *) s->val,
1325	    SANE_UNFIX(s->val[OPT_TL_X].w), SANE_UNFIX(s->val[OPT_TL_Y].w),
1326	    SANE_UNFIX(s->val[OPT_BR_X].w), SANE_UNFIX(s->val[OPT_BR_Y].w));
1327
1328	/*
1329	 * Calculate bytes_per_pixel and bytes_per_line for
1330	 * any color depths.
1331	 *
1332	 * The default color depth is stored in mode_params.depth:
1333	 */
1334
1335	if (mode_params[s->val[OPT_MODE].w].depth == 1)
1336		s->params.depth = 1;
1337	else
1338		s->params.depth = s->val[OPT_BIT_DEPTH].w;
1339
1340	if (s->params.depth > 8) {
1341		s->params.depth = 16;	/*
1342					 * The frontends can only handle 8 or 16 bits
1343					 * for gray or color - so if it's more than 8,
1344					 * it gets automatically set to 16. This works
1345					 * as long as EPSON does not come out with a
1346					 * scanner that can handle more than 16 bits
1347					 * per color channel.
1348					 */
1349	}
1350
1351	/* this works because it can only be set to 1, 8 or 16 */
1352	bytes_per_pixel = s->params.depth / 8;
1353	if (s->params.depth % 8) {	/* just in case ... */
1354		bytes_per_pixel++;
1355	}
1356
1357	/* pixels_per_line is rounded to the next 8bit boundary */
1358	s->params.pixels_per_line = s->params.pixels_per_line & ~7;
1359
1360	s->params.last_frame = SANE_TRUE;
1361
1362	switch (s->val[OPT_MODE].w) {
1363	case MODE_BINARY:
1364	case MODE_GRAY:
1365		s->params.format = SANE_FRAME_GRAY;
1366		s->params.bytes_per_line =
1367			s->params.pixels_per_line * s->params.depth / 8;
1368		break;
1369	case MODE_COLOR:
1370		s->params.format = SANE_FRAME_RGB;
1371		s->params.bytes_per_line =
1372			3 * s->params.pixels_per_line * bytes_per_pixel;
1373		break;
1374#ifdef SANE_FRAME_IR
1375	case MODE_INFRARED:
1376		s->params.format = SANE_FRAME_IR;
1377		s->params.bytes_per_line =
1378			s->params.pixels_per_line * s->params.depth / 8;
1379		break;
1380#endif
1381	}
1382
1383	if (s->params.bytes_per_line == 0)
1384		return SANE_STATUS_INVAL;
1385
1386	/*
1387	 * Calculate correction for line_distance in D1 scanner:
1388	 * Start line_distance lines earlier and add line_distance lines at the end
1389	 *
1390	 * Because the actual line_distance is not yet calculated we have to do this
1391	 * first.
1392	 */
1393
1394	s->hw->color_shuffle = SANE_FALSE;
1395
1396	s->lines_written = 0;
1397	s->color_shuffle_line = 0;
1398	s->current_output_line = 0;
1399
1400	if ((s->hw->optical_res != 0) && (mparam->depth == 8)
1401	    && (mparam->flags != 0)) {
1402
1403		s->line_distance =
1404			s->hw->max_line_distance * dpi / s->hw->optical_res;
1405
1406		if (s->line_distance != 0) {
1407
1408			s->hw->color_shuffle = SANE_TRUE;
1409
1410			DBG(1, "%s: color shuffling required\n",  __func__);
1411		}
1412	}
1413
1414	/*
1415	 * If (s->top + s->params.lines) is larger than the max scan area, reset
1416	 * the number of scan lines:
1417	 * XXX: precalculate the maximum scanning area elsewhere (use dev max_y)
1418	 */
1419
1420	if (SANE_UNFIX(s->val[OPT_BR_Y].w) / MM_PER_INCH * dpi <
1421	    (s->params.lines + s->top)) {
1422		s->params.lines =
1423			((int) SANE_UNFIX(s->val[OPT_BR_Y].w) / MM_PER_INCH *
1424			 dpi + 0.5) - s->top;
1425	}
1426
1427	s->block = SANE_FALSE;
1428	s->lcount = 1;
1429
1430	/*
1431	 * The set line count commands needs to be sent for certain scanners in
1432	 * color mode. The D1 level requires it, we are however only testing for
1433	 * 'D' and not for the actual numeric level.
1434	 */
1435
1436	if ((s->hw->cmd->level[0] == 'B') && (s->hw->level >= 5)) /* >= B5 */
1437		e2_setup_block_mode(s);
1438
1439	else if ((s->hw->cmd->level[0] == 'B') && (s->hw->level == 4) /* B4 !color */
1440		&& (!mode_params[s->val[OPT_MODE].w].color))
1441		e2_setup_block_mode(s);
1442
1443	else if (s->hw->cmd->level[0] == 'D') /* Dx */
1444		e2_setup_block_mode(s);
1445
1446	return (s->params.lines > 0) ? SANE_STATUS_GOOD : SANE_STATUS_INVAL;
1447}
1448
1449void
1450e2_wait_button(Epson_Scanner * s)
1451{
1452	DBG(5, "%s\n", __func__);
1453
1454	s->hw->wait_for_button = SANE_TRUE;
1455
1456	while (s->hw->wait_for_button == SANE_TRUE) {
1457		unsigned char button_status = 0;
1458
1459		if (s->canceling == SANE_TRUE)
1460			s->hw->wait_for_button = SANE_FALSE;
1461
1462		/* get the button status from the scanner */
1463		else if (esci_request_push_button_status(s, &button_status) ==
1464			 SANE_STATUS_GOOD) {
1465			if (button_status)
1466				s->hw->wait_for_button = SANE_FALSE;
1467			else
1468				sleep(1);
1469		} else {
1470			/* we ran into an error condition, just continue */
1471			s->hw->wait_for_button = SANE_FALSE;
1472		}
1473	}
1474}
1475
1476/*
1477SANE_Status
1478e2_check_extended_status(Epson_Scanner *s)
1479{
1480
1481	SANE_Status status = esci_request_scanner_status(s, buf);
1482	if (status != SANE_STATUS_GOOD)
1483			return status;
1484
1485	if (buf[0] & FSF_STATUS_MAIN_WU)
1486
1487	main -> 0
1488	fbf -> 3
1489	adf -> 1, 10
1490	tpu -> 2
1491}
1492*/
1493
1494SANE_Status
1495e2_check_warm_up(Epson_Scanner * s, SANE_Bool * wup)
1496{
1497	SANE_Status status;
1498
1499	DBG(5, "%s\n", __func__);
1500
1501	*wup = SANE_FALSE;
1502
1503	if (s->hw->extended_commands) {
1504		unsigned char buf[16];
1505
1506		status = esci_request_scanner_status(s, buf);
1507		if (status != SANE_STATUS_GOOD)
1508			return status;
1509
1510		if (buf[0] & FSF_STATUS_MAIN_WU)
1511			*wup = SANE_TRUE;
1512
1513	} else {
1514		unsigned char *es;
1515
1516		/* this command is not available on some scanners */
1517		if (!s->hw->cmd->request_extended_status)
1518			return SANE_STATUS_GOOD;
1519
1520		status = esci_request_extended_status(s, &es, NULL);
1521		if (status != SANE_STATUS_GOOD)
1522			return status;
1523
1524		if (es[0] & EXT_STATUS_WU)
1525			*wup = SANE_TRUE;
1526
1527		free(es);
1528	}
1529
1530	return status;
1531}
1532
1533SANE_Status
1534e2_wait_warm_up(Epson_Scanner * s)
1535{
1536	SANE_Status status;
1537	SANE_Bool wup;
1538
1539	DBG(5, "%s\n", __func__);
1540
1541	s->retry_count = 0;
1542
1543	while (1) {
1544
1545		if (s->canceling)
1546			return SANE_STATUS_CANCELLED;
1547
1548		status = e2_check_warm_up(s, &wup);
1549		if (status != SANE_STATUS_GOOD)
1550			return status;
1551
1552		if (wup == SANE_FALSE)
1553			break;
1554
1555		s->retry_count++;
1556
1557		if (s->retry_count > SANE_EPSON_MAX_RETRIES) {
1558			DBG(1, "max retry count exceeded (%d)\n",
1559			    s->retry_count);
1560			return SANE_STATUS_DEVICE_BUSY;
1561		}
1562		sleep(5);
1563	}
1564
1565	return SANE_STATUS_GOOD;
1566}
1567
1568SANE_Status
1569e2_check_adf(Epson_Scanner * s)
1570{
1571	SANE_Status status;
1572
1573	DBG(5, "%s\n", __func__);
1574
1575	if (s->hw->use_extension == SANE_FALSE)
1576		return SANE_STATUS_GOOD;
1577
1578	if (s->hw->extended_commands) {
1579		unsigned char buf[16];
1580
1581		status = esci_request_scanner_status(s, buf);
1582		if (status != SANE_STATUS_GOOD)
1583			return status;
1584
1585		if (buf[1] & FSF_STATUS_ADF_PE)
1586			return SANE_STATUS_NO_DOCS;
1587
1588		if (buf[1] & FSF_STATUS_ADF_PJ)
1589			return SANE_STATUS_JAMMED;
1590
1591	} else {
1592		unsigned char *buf, t;
1593
1594		status = esci_request_extended_status(s, &buf, NULL);
1595		if (status != SANE_STATUS_GOOD)
1596			return status;
1597
1598		t = buf[1];
1599
1600		free(buf);
1601
1602		if (t & EXT_STATUS_PE)
1603			return SANE_STATUS_NO_DOCS;
1604
1605		if (t & EXT_STATUS_PJ)
1606			return SANE_STATUS_JAMMED;
1607	}
1608
1609	return SANE_STATUS_GOOD;
1610}
1611
1612SANE_Status
1613e2_start_std_scan(Epson_Scanner * s)
1614{
1615	SANE_Status status;
1616	unsigned char params[2];
1617
1618	DBG(5, "%s\n", __func__);
1619
1620	/* ESC g */
1621	params[0] = ESC;
1622	params[1] = s->hw->cmd->start_scanning;
1623
1624	e2_send(s, params, 2, 6 + (s->lcount * s->params.bytes_per_line),
1625		&status);
1626
1627	return status;
1628}
1629
1630SANE_Status
1631e2_start_ext_scan(Epson_Scanner * s)
1632{
1633	SANE_Status status;
1634	unsigned char params[2];
1635	unsigned char buf[14];
1636
1637	DBG(5, "%s\n", __func__);
1638
1639	params[0] = FS;
1640	params[1] = 'G';
1641
1642	status = e2_txrx(s, params, 2, buf, 14);
1643	if (status != SANE_STATUS_GOOD)
1644		return status;
1645
1646	if (buf[0] != STX)
1647		return SANE_STATUS_INVAL;
1648
1649	if (buf[1] & STATUS_FER) {
1650		DBG(1, "%s: fatal error\n", __func__);
1651		return SANE_STATUS_IO_ERROR;
1652	}
1653
1654	/*
1655	 * The 12000XL signals busy only with FS+G, all other status queries
1656	 * say non-busy. Probably because you can in deed communicate with the
1657	 * device, just scanning is not yet possible. I tried polling with FS+G
1658	 * every 5 seconds, but that made scary noises. So, bail out and let
1659	 * the user retry manually.
1660	 */
1661	if (buf[1] & STATUS_NOT_READY) {
1662		DBG(1, "%s: device not ready\n", __func__);
1663		return SANE_STATUS_DEVICE_BUSY;
1664	}
1665
1666	s->ext_block_len = le32atoh(&buf[2]);
1667	s->ext_blocks = le32atoh(&buf[6]);
1668	s->ext_last_len = le32atoh(&buf[10]);
1669
1670	s->ext_counter = 0;
1671
1672	DBG(5, " status         : 0x%02x\n", buf[1]);
1673	DBG(5, " block size     : %u\n", (unsigned int) le32atoh(&buf[2]));
1674	DBG(5, " block count    : %u\n", (unsigned int) le32atoh(&buf[6]));
1675	DBG(5, " last block size: %u\n", (unsigned int) le32atoh(&buf[10]));
1676
1677	if (s->ext_last_len) {
1678		s->ext_blocks++;
1679		DBG(1, "adjusted block count: %d\n", s->ext_blocks);
1680	}
1681
1682	/* adjust block len if we have only one block to read */
1683	if (s->ext_block_len == 0 && s->ext_last_len)
1684		s->ext_block_len = s->ext_last_len;
1685
1686	return status;
1687}
1688
1689void
1690e2_scan_finish(Epson_Scanner * s)
1691{
1692	DBG(5, "%s\n", __func__);
1693
1694	free(s->buf);
1695	s->buf = NULL;
1696
1697	if (s->hw->ADF && s->hw->use_extension && s->val[OPT_AUTO_EJECT].w)
1698		if (e2_check_adf(s) == SANE_STATUS_NO_DOCS)
1699			esci_eject(s);
1700}
1701
1702void
1703e2_copy_image_data(Epson_Scanner * s, SANE_Byte * data, SANE_Int max_length,
1704		   SANE_Int * length)
1705{
1706	if (!s->block && s->params.format == SANE_FRAME_RGB) {
1707
1708		max_length /= 3;
1709
1710		if (max_length > s->end - s->ptr)
1711			max_length = s->end - s->ptr;
1712
1713		*length = 3 * max_length;
1714
1715		while (max_length-- != 0) {
1716			*data++ = s->ptr[0];
1717			*data++ = s->ptr[s->params.pixels_per_line];
1718			*data++ = s->ptr[2 * s->params.pixels_per_line];
1719			++s->ptr;
1720		}
1721
1722	} else {
1723		if (max_length > s->end - s->ptr)
1724			max_length = s->end - s->ptr;
1725
1726		*length = max_length;
1727
1728		if (s->params.depth == 1) {
1729			while (max_length-- != 0)
1730				*data++ = ~*s->ptr++;
1731		} else {
1732			memcpy(data, s->ptr, max_length);
1733			s->ptr += max_length;
1734		}
1735	}
1736}
1737
1738SANE_Status
1739e2_ext_read(struct Epson_Scanner *s)
1740{
1741	struct Epson_Device *dev = s->hw;
1742	SANE_Status status = SANE_STATUS_GOOD;
1743	ssize_t buf_len = 0, read;
1744
1745	DBG(18, "%s: begin\n", __func__);
1746
1747	/* did we passed everything we read to sane? */
1748	if (s->ptr == s->end) {
1749
1750		if (s->eof)
1751			return SANE_STATUS_EOF;
1752
1753		s->ext_counter++;
1754
1755		/* sane has already got the data, read some more, the final
1756		 * error byte must not be included in buf_len
1757		 */
1758		buf_len = s->ext_block_len;
1759
1760		if (s->ext_counter == s->ext_blocks && s->ext_last_len)
1761			buf_len = s->ext_last_len;
1762
1763		DBG(18, "%s: block %d/%d, size %lu\n", __func__,
1764			s->ext_counter, s->ext_blocks,
1765			(unsigned long) buf_len);
1766
1767		/* receive image data + error code */
1768		read = e2_recv(s, s->buf, buf_len + 1, &status);
1769
1770		DBG(18, "%s: read %lu bytes, status: %d\n", __func__, (unsigned long) read, status);
1771
1772		if (status != SANE_STATUS_GOOD) {
1773			e2_cancel(s);
1774			return status;
1775		}
1776
1777		if (e2_dev_model(dev, "GT-8200") || e2_dev_model(dev, "Perfection1650")) {
1778			/* See http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=597922#127 */
1779			s->buf[buf_len] &= 0xc0;
1780		}
1781
1782		if (s->buf[buf_len] & FSG_STATUS_CANCEL_REQ) {
1783			DBG(0, "%s: cancel request received\n", __func__);
1784			e2_cancel(s);
1785			return SANE_STATUS_CANCELLED;
1786		}
1787
1788		if (s->buf[buf_len] & (FSG_STATUS_FER | FSG_STATUS_NOT_READY))
1789			return SANE_STATUS_IO_ERROR;
1790
1791		/* ack every block except the last one */
1792		if (s->ext_counter < s->ext_blocks) {
1793			size_t next_len = s->ext_block_len;
1794
1795			if (s->ext_counter == (s->ext_blocks - 1))
1796				next_len = s->ext_last_len;
1797
1798			if (s->canceling) {
1799				e2_cancel(s);
1800				return SANE_STATUS_CANCELLED;
1801			}
1802
1803			status = e2_ack_next(s, next_len + 1);
1804		} else
1805			s->eof = SANE_TRUE;
1806
1807		s->end = s->buf + buf_len;
1808		s->ptr = s->buf;
1809	}
1810
1811	return status;
1812}
1813
1814/* XXXX use routine from sane-evolution */
1815
1816typedef struct
1817{
1818	unsigned char code;
1819	unsigned char status;
1820
1821	unsigned char buf[4];
1822
1823} EpsonDataRec;
1824
1825
1826/* XXX this routine is ugly and should be avoided */
1827static SANE_Status
1828read_info_block(Epson_Scanner * s, EpsonDataRec * result)
1829{
1830	SANE_Status status;
1831	unsigned char params[2];
1832
1833      retry:
1834	e2_recv(s, result, s->block ? 6 : 4, &status);
1835	if (status != SANE_STATUS_GOOD)
1836		return status;
1837
1838	if (result->code != STX) {
1839		DBG(1, "error: got %02x, expected STX\n", result->code);
1840		return SANE_STATUS_INVAL;
1841	}
1842
1843	/* XXX */
1844	if (result->status & STATUS_FER) {
1845		unsigned char *ext_status;
1846
1847		DBG(1, "fatal error, status = %02x\n", result->status);
1848
1849		if (s->retry_count > SANE_EPSON_MAX_RETRIES) {
1850			DBG(1, "max retry count exceeded (%d)\n",
1851			    s->retry_count);
1852			return SANE_STATUS_INVAL;
1853		}
1854
1855		/* if the scanner is warming up, retry after a few secs */
1856		status = esci_request_extended_status(s, &ext_status, NULL);
1857		if (status != SANE_STATUS_GOOD)
1858			return status;
1859
1860		if (ext_status[0] & EXT_STATUS_WU) {
1861			free(ext_status);
1862
1863			sleep(5);	/* for the next attempt */
1864
1865			DBG(1, "retrying ESC G - %d\n", ++(s->retry_count));
1866
1867			params[0] = ESC;
1868			params[1] = s->hw->cmd->start_scanning;
1869
1870			e2_send(s, params, 2, 0, &status);
1871			if (status != SANE_STATUS_GOOD)
1872				return status;
1873
1874			goto retry;
1875		} else
1876			free(ext_status);
1877	}
1878
1879	return status;
1880}
1881
1882static SANE_Status
1883color_shuffle(SANE_Handle handle, int *new_length)
1884{
1885	Epson_Scanner *s = (Epson_Scanner *) handle;
1886	SANE_Byte *buf = s->buf;
1887	int length = s->end - s->buf;
1888
1889		SANE_Byte *data_ptr;	/* ptr to data to process */
1890		SANE_Byte *data_end;	/* ptr to end of processed data */
1891		SANE_Byte *out_data_ptr;	/* ptr to memory when writing data */
1892		int i;		/* loop counter */
1893
1894		/*
1895		 * It looks like we are dealing with a scanner that has an odd way
1896		 * of dealing with colors... The red and blue scan lines are shifted
1897		 * up or down by a certain number of lines relative to the green line.
1898		 */
1899		DBG(5, "%s\n", __func__);
1900
1901		/*
1902		 * Initialize the variables we are going to use for the
1903		 * copying of the data. data_ptr is the pointer to
1904		 * the currently worked on scan line. data_end is the
1905		 * end of the data area as calculated from adding *length
1906		 * to the start of data.
1907		 * out_data_ptr is used when writing out the processed data
1908		 * and always points to the beginning of the next line to
1909		 * write.
1910		 */
1911		data_ptr = out_data_ptr = buf;
1912		data_end = data_ptr + length;
1913
1914		/*
1915		 * The image data is in *buf, we know that the buffer contains s->end - s->buf ( = length)
1916		 * bytes of data. The width of one line is in s->params.bytes_per_line
1917		 *
1918		 * The buffer area is supposed to have a number of full scan
1919		 * lines, let's test if this is the case.
1920		 */
1921
1922		if (length % s->params.bytes_per_line != 0) {
1923			DBG(1, "error in buffer size: %d / %d\n", length,
1924			    s->params.bytes_per_line);
1925			return SANE_STATUS_INVAL;
1926		}
1927
1928		while (data_ptr < data_end) {
1929			SANE_Byte *source_ptr, *dest_ptr;
1930			int loop;
1931
1932			/* copy the green information into the current line */
1933
1934			source_ptr = data_ptr + 1;
1935			dest_ptr = s->line_buffer[s->color_shuffle_line] + 1;
1936
1937			for (i = 0; i < s->params.bytes_per_line / 3; i++) {
1938				*dest_ptr = *source_ptr;
1939				dest_ptr += 3;
1940				source_ptr += 3;
1941			}
1942
1943			/* copy the red information n lines back */
1944
1945			if (s->color_shuffle_line >= s->line_distance) {
1946				source_ptr = data_ptr + 2;
1947				dest_ptr =
1948					s->line_buffer[s->color_shuffle_line -
1949						       s->line_distance] + 2;
1950
1951/*				while (source_ptr < s->line_buffer[s->color_shuffle_line] + s->params.bytes_per_line) */
1952				for (loop = 0;
1953				     loop < s->params.bytes_per_line / 3;
1954				     loop++) {
1955					*dest_ptr = *source_ptr;
1956					dest_ptr += 3;
1957					source_ptr += 3;
1958				}
1959			}
1960
1961			/* copy the blue information n lines forward */
1962
1963			source_ptr = data_ptr;
1964			dest_ptr =
1965				s->line_buffer[s->color_shuffle_line +
1966					       s->line_distance];
1967
1968/*			while (source_ptr < s->line_buffer[s->color_shuffle_line] + s->params.bytes_per_line) */
1969			for (loop = 0; loop < s->params.bytes_per_line / 3;
1970			     loop++) {
1971				*dest_ptr = *source_ptr;
1972				dest_ptr += 3;
1973				source_ptr += 3;
1974			}
1975
1976			data_ptr += s->params.bytes_per_line;
1977
1978			if (s->color_shuffle_line == s->line_distance) {
1979				/*
1980				 * We just finished the line in line_buffer[0] - write it to the
1981				 * output buffer and continue.
1982				 *
1983				 * The output buffer is still "buf", but because we are
1984				 * only overwriting from the beginning of the memory area
1985				 * we are not interfering with the "still to shuffle" data
1986				 * in the same area.
1987				 */
1988
1989				/*
1990				 * Strip the first and last n lines and limit to
1991				 */
1992				if ((s->current_output_line >=
1993				     s->line_distance)
1994				    && (s->current_output_line <
1995					s->params.lines + s->line_distance)) {
1996					memcpy(out_data_ptr,
1997					       s->line_buffer[0],
1998					       s->params.bytes_per_line);
1999					out_data_ptr +=
2000						s->params.bytes_per_line;
2001
2002					s->lines_written++;
2003				}
2004
2005				s->current_output_line++;
2006
2007				/*
2008				 * Now remove the 0-entry and move all other
2009				 * lines up by one. There are 2*line_distance + 1
2010				 * buffers, * therefore the loop has to run from 0
2011				 * to * 2*line_distance, and because we want to
2012				 * copy every n+1st entry to n the loop runs
2013				 * from - to 2*line_distance-1!
2014				 */
2015
2016				free(s->line_buffer[0]);
2017
2018				for (i = 0; i < s->line_distance * 2; i++) {
2019					s->line_buffer[i] =
2020						s->line_buffer[i + 1];
2021				}
2022
2023				/*
2024				 * and create one new buffer at the end
2025				 */
2026
2027				s->line_buffer[s->line_distance * 2] =
2028					malloc(s->params.bytes_per_line);
2029				if (s->line_buffer[s->line_distance * 2] ==
2030				    NULL) {
2031					DBG(1, "out of memory (line %d)\n",
2032					    __LINE__);
2033					return SANE_STATUS_NO_MEM;
2034				}
2035			} else {
2036				s->color_shuffle_line++;	/* increase the buffer number */
2037			}
2038		}
2039
2040		/*
2041		 * At this time we've used up all the new data from the scanner, some of
2042		 * it is still in the line_buffers, but we are ready to return some of it
2043		 * to the front end software. To do so we have to adjust the size of the
2044		 * data area and the *new_length variable.
2045		 */
2046
2047		*new_length = out_data_ptr - buf;
2048
2049	return SANE_STATUS_GOOD;
2050}
2051
2052static inline int
2053get_color(int status)
2054{
2055	switch ((status >> 2) & 0x03) {
2056	case 1:
2057		return 1;
2058	case 2:
2059		return 0;
2060	case 3:
2061		return 2;
2062	default:
2063		return 0;	/* required to make the compiler happy */
2064	}
2065}
2066
2067
2068SANE_Status
2069e2_block_read(struct Epson_Scanner *s)
2070{
2071	SANE_Status status;
2072	SANE_Bool reorder = SANE_FALSE;
2073
2074      START_READ:
2075	DBG(18, "%s: begin\n", __func__);
2076
2077	if (s->ptr == s->end) {
2078		EpsonDataRec result;
2079		unsigned int buf_len;
2080
2081		if (s->eof) {
2082			if (s->hw->color_shuffle) {
2083				DBG(1,
2084				    "written %d lines after color shuffle\n",
2085				    s->lines_written);
2086				DBG(1, "lines requested: %d\n",
2087				    s->params.lines);
2088			}
2089
2090			return SANE_STATUS_EOF;
2091		}
2092
2093		status = read_info_block(s, &result);
2094		if (status != SANE_STATUS_GOOD) {
2095			return status;
2096		}
2097
2098		buf_len = result.buf[1] << 8 | result.buf[0];
2099		buf_len *= (result.buf[3] << 8 | result.buf[2]);
2100
2101		DBG(18, "%s: buf len = %u\n", __func__, buf_len);
2102
2103		{
2104			/* do we have to reorder the data ? */
2105			if (get_color(result.status) == 0x01)
2106				reorder = SANE_TRUE;
2107
2108			e2_recv(s, s->buf, buf_len, &status);
2109			if (status != SANE_STATUS_GOOD) {
2110				return status;
2111			}
2112		}
2113
2114		if (result.status & STATUS_AREA_END) {
2115			DBG(1, "%s: EOF\n", __func__);
2116			s->eof = SANE_TRUE;
2117		} else {
2118			if (s->canceling) {
2119				e2_cancel(s);
2120				return SANE_STATUS_CANCELLED;
2121			} else {
2122				status = e2_ack(s);
2123			}
2124		}
2125
2126		s->end = s->buf + buf_len;
2127		s->ptr = s->buf;
2128
2129		/*
2130		 * if we have to re-order the color components (GRB->RGB) we
2131		 * are doing this here:
2132		 */
2133
2134		/*
2135		 * Certain Perfection 1650 also need this re-ordering of the two
2136		 * color channels. These scanners are identified by the problem
2137		 * with the half vertical scanning area. When we corrected this,
2138		 * we also set the variable s->hw->need_color_reorder
2139		 */
2140		if (s->hw->need_color_reorder)
2141			reorder = SANE_FALSE;	/* reordering once is enough */
2142
2143		if (reorder && s->params.format == SANE_FRAME_RGB) {
2144			SANE_Byte *ptr;
2145
2146			ptr = s->buf;
2147			while (ptr < s->end) {
2148				if (s->params.depth > 8) {
2149					SANE_Byte tmp;
2150
2151					/* R->G G->R */
2152					tmp = ptr[0];
2153					ptr[0] = ptr[2];	/* first Byte G */
2154					ptr[2] = tmp;	/* first Byte R */
2155
2156					tmp = ptr[1];
2157					ptr[1] = ptr[3];	/* second Byte G */
2158					ptr[3] = tmp;	/* second Byte R */
2159
2160					ptr += 6;	/* go to next pixel */
2161				} else {
2162					/* R->G G->R */
2163					SANE_Byte tmp;
2164
2165					tmp = ptr[0];
2166					ptr[0] = ptr[1];	/* G */
2167					ptr[1] = tmp;	/* R */
2168					/* B stays the same */
2169					ptr += 3;	/* go to next pixel */
2170				}
2171			}
2172		}
2173
2174		/*
2175		 * Do the color_shuffle if everything else is correct - at this time
2176		 * most of the stuff is hardcoded for the Perfection 610
2177		 */
2178
2179		if (s->hw->color_shuffle) {
2180			int new_length = 0;
2181
2182			status = color_shuffle(s, &new_length);
2183			/* XXX check status here */
2184
2185			/*
2186			 * If no bytes are returned, check if the scanner is already done, if so,
2187			 * we'll probably just return, but if there is more data to process get
2188			 * the next batch.
2189			 */
2190			if (new_length == 0 && s->end != s->ptr)
2191				goto START_READ;
2192
2193			s->end = s->buf + new_length;
2194			s->ptr = s->buf;
2195		}
2196
2197		DBG(18, "%s: begin scan2\n", __func__);
2198	}
2199
2200	DBG(18, "%s: end\n", __func__);
2201
2202	return SANE_STATUS_GOOD;
2203}
2204