## 4.3 Operations

### 4.3.1 `sane_init`

This function must be called before any other SANE function can be called. The behavior of a SANE backend is undefined if this function is not called first or if the status code returned by `sane_init` is different from `SANE_STATUS_GOOD`. The version code of the backend is returned in the value pointed to by `version_code`. If that pointer is `NULL`, no version code is returned. Argument `authorize` is either a pointer to a function that is invoked when the backend requires authentication for a specific resource or `NULL` if the frontend does not support authentication.

>     SANE_Status sane_init (SANE_Int * version_code,
>                            SANE_Authorization_Callback authorize);

The authorization function may be called by a backend in response to any of the following calls:

> `sane_open`, `sane_control_option`, `sane_start`

If a backend was initialized without authorization function, then authorization requests that cannot be handled by the backend itself will fail automatically and the user may be prevented from accessing protected resources. Backends are encouraged to implement means of authentication that do not require user assistance. E.g., on a multi-user system that authenticates users through a login process a backend could automatically lookup the apporpriate password based on resource- and user-name.

The authentication function type has the following declaration:

>     #define SANE_MAX_USERNAME_LEN   128
>     #define SANE_MAX_PASSWORD_LEN   128

>     typedef void (*SANE_Authorization_Callback)
>         (SANE_String_Const resource,
>          SANE_Char username[SANE_MAX_USERNAME_LEN],
>          SANE_Char password[SANE_MAX_PASSWORD_LEN]);

Three arguments are passed to the authorization function: `resource` is a string specifying the name of the resource that requires authorization. A frontend should use this string to build a user-prompt requesting a username and a password. The `username` and `password` arguments are (pointers to) an array of `SANE_MAX_USERNAME_LEN` and `SANE_MAX_PASSWORD_LEN` characters, respectively. The authorization call should place the entered username and password in these arrays. The returned strings must be ASCII-NUL terminated.

### 4.3.2 `sane_exit`

This function must be called to terminate use of a backend. The function will first close all device handles that still might be open (it is recommended to close device handles explicitly through a call to `sane_close()`, but backends are required to release all resources upon a call to this function). After this function returns, no function other than `sane_init()` may be called (regardless of the status value returned by `sane_exit()`. Neglecting to call this function may result in some resources not being released properly.

>     void sane_exit (void);

### 4.3.3 `sane_get_devices`

This function can be used to query the list of devices that are available. If the function executes successfully, it stores a pointer to a `NULL` terminated array of pointers to `SANE_Device` structures in `*device_list`. The returned list is guaranteed to remain unchanged and valid until (a) another call to this function is performed or (b) a call to `sane_exit()` is performed. This function can be called repeatedly to detect when new devices become available. If argument `local_only` is true, only local devices are returned (devices directly attached to the machine that SANE is running on). If it is false, the device list includes all remote devices that are accessible to the SANE library.

>     SANE_Status sane_get_devices (const SANE_Device *** device_list,
>                                   SANE_Bool local_only);

This function may fail with `SANE_STATUS_NO_MEM` if an insufficient amount of memory is available.

> Backend Implementation Note
> SANE does not require that this function is called before a `sane_open()` call is performed. A device name may be specified explicitly by a user which would make it unnecessary and undesirable to call this function first. The same information about a device has to be returned when `sane_open` is called.

### 4.3.4 `sane_open`

This function is used to establish a connection to a particular device. The name of the device to be opened is passed in argument `name`. If the call completes successfully, a handle for the device is returned in `*h`. The description of the device is returned in `**device_description`. This is the same description that is returned in the list by `sane_get_devices`. The returned data `*h` and `*device_description` is guaranteed to remain unchanged and valid until a call to `sane_close()` is performed. As a special case, specifying a zero-length string as the device requests opening the first available device (if there is such a device).

>     SANE_Status sane_open (SANE_String_Const name, SANE_Handle * h,
>     const SANE_Device ** device_description);

This function may fail with one of the following status codes.

> `SANE_STATUS_DEVICE_BUSY`:
>   The device is currently busy (in use by somebody else).
> `SANE_STATUS_INVAL`:
>   The device name is not valid.
> `SANE_STATUS_IO_ERROR`:
>   An error occured while communicating with the device.
> `SANE_STATUS_NO_MEM`:
>   An insufficent amount of memory is available.
> `SANE_STATUS_ACCESS_DENIED`:
>   Access to the device has been denied due to insufficient or invalid authentication.

### 4.3.5 `sane_close`

This function terminates the association between the device handle passed in argument `h` and the device it represents. If the device is presently active, a call to `sane_cancel()` is performed first. After this function returns, handle `h` must not be used anymore.

>     void sane_close (SANE_Handle h);

### 4.3.6 `sane_get_option_descriptor`

This function is used to access option descriptors. The function returns the option descriptor for option number `n` of the device represented by handle `h`. Option number 0 is guaranteed to be a valid option. Its value is an integer that specifies the number of options that are available for device handle `h` (the count includes option 0). If n is not a valid option index, the function returns `NULL`. The returned option descriptor is guaranteed to remain valid (and at the returned address) until the device is closed.

>     const SANE_Option_Descriptor *
>         sane_get_option_descriptor (SANE_Handle h, SANE_Int n);

### 4.3.7 `sane_control_option`

This function is used to set or inquire the current value of option number `n` of the device represented by handle `h`. The manner in which the option is controlled is specified by parameter `a`. The possible values of this parameter are described in more detail below. The value of the option is passed through argument `v`. It is a pointer to the memory that holds the option value. The memory area pointed to by `v` must be big enough to hold the entire option value (determined by member `size` in the corresponding option descriptor). The only exception to this rule is that when setting the value of a string option, the string pointed to by argument `v` may be shorter since the backend will stop reading the option value upon encountering the first `NUL` terminator in the string. If argument `i` is not `NULL`, the value of `*i` will be set to provide details on how well the request has been met. The meaning of this argument is described in more detail below.

>     SANE_Status sane_control_option (SANE_Handle h, SANE_Int n,
>                                      SANE_Action a, void *v,
>                                      SANE_Int * i);

The way the option is affected by a call to this function is controlled by parameter `a` which is a value of type `SANE_Action`. The possible values and their meaning is described in Table 7.

Symbol | Code | Description
`SANE_ACTION_GET_VALUE` | 0 | Get current option value.
`SANE_ACTION_SET_VALUE` | 1 | Set option value. The option value passed through argument `v` may be modified by the backend if the value cannot be set exactly.
`SANE_ACTION_SET_AUTO` | 2 | Turn on automatic mode. Backend or device will automatically select an appropriate value. This mode remains effective until overridden by an explicit set value request. The value of parameter `v` is completely ignored in this case and may be `NULL`.

Table 7: Action Values (`SANE_Action`)

After setting a value via an action value of `SANE_ACTION_SET_VALUE`, additional information on how well the request has been met is returned in `*i` (if `i` is non-`NULL`). The returned value is a bitset that may contain any combination of the values described in Table 8.

Symbol | Code | Description

`SANE_INFO_INEXACT`

1

This value is returned when setting an option value resulted in a value being selected that does not exactly match the requested value. For example, if a scanner can adjust the resolution in increments of 30dpi only, setting the resolution to 307dpi may result in an actual setting of 300dpi. When this happens, the bitset returned in `*i` has this member set. In addition, the option value is modified to reflect the actual (rounded) value that was used by the backend. Note that inexact values are admissible for strings as well. A backend may choose to ``round'' a string to the closest matching legal string for a constrained string value.

`SANE_INFO_RELOAD_OPTIONS` | 2 | The setting of an option may affect the value or availability of one or more other options. When this happens, the SANE backend sets this member in `*i` to indicate that the application should reload all options. This member may be set if and only if at least one option changed.
`SANE_INFO_RELOAD_PARAMS` | 4 | The setting of an option may affect the parameter values (see `sane_get_parameters()`). If setting an option affects the parameter values, this member will be set in `*i`. Note that this member may be set even if the parameters did not actually change. However, it is guaranteed that the parameters never change without this member being set.

Table 8: Additional Information Returned When Setting an Option

This function may fail with one of the following status codes.

> `SANE_STATUS_UNSUPPORTED`:
>   The operation is not supported for the specified handle and option number.
> `SANE_STATUS_INVAL`:
>   The option value is not valid.
> `SANE_STATUS_IO_ERROR`:
>   An error occured while communicating with the device.
> `SANE_STATUS_NO_MEM`:
>   An insufficent amount of memory is available.
> `SANE_STATUS_ACCESS_DENIED`:
>   Access to the option has been denied due to insufficient or invalid authentication.

### 4.3.8 `sane_get_parameters`

This function is used to obtain the current scan parameters. The returned parameters are guaranteed to be accurate between the time a scan has been started (`sane_start()` has been called) and the completion of that request. Outside of that window, the returned values are best-effort estimates of what the parameters will be when `sane_start()` gets invoked. Calling this function before a scan has actually started allows, for example, to get an estimate of how big the scanned image will be. The parameters passed to this function are the handle `h` of the device for which the parameters should be obtained and a pointer `p` to a parameter structure. The parameter structure is described in more detail below.

>     SANE_Status sane_get_parameters (SANE_Handle h,
>                                      SANE_Parameters * p);

The scan parameters are returned in a structure of type `SANE_Parameters`. The C declaration of this structure is given below.

>     typedef struct
>       {
>         SANE_Frame format;
>         SANE_Int flags;
>         SANE_Int lines;
>         SANE_Int depth;
>         SANE_Int pixels_per_line;
>         SANE_Int bytes_per_line;
>         SANE_Int channels_per_image;
>         SANE_String format_desc;
>         SANE_String proposed_filename;
>         SANE_Int dpi_x;
>         SANE_Int dpi_y;
>         char reserved[32]; /* 32 bytes for future use */
>       }
>     SANE_Parameters;

Member `format` specifies the format of the next frame to be returned. The possible values for type `SANE_Frame` are described in Table 9. The meaning of these values is described in more detail in Section 3.2.

Symbol | Code | SANE standard | Description
`SANE_FRAME_GRAY` | 0 | version 1 | Band covering human visual range.
`SANE_FRAME_RGB` | 1 | version 1 | Pixel-interleaved red/green/blue bands.
`SANE_FRAME_RED` | 2 | version 1 | Red band of a red/green/blue image.
`SANE_FRAME_GREEN` | 3 | version 1 | Green band of a red/green/blue image.
`SANE_FRAME_BLUE` | 4 | version 1 | Blue band of a red/green/blue image.
`SANE_FRAME_RAW` | 5 | version 2 | Arbitrary pixel property transmission.
`SANE_FRAME_MIME` | 6 | version 2 | Data described by a mime descriptor.

Table 9: Frame Format (`SANE_Frame`)

The `flags` member is a 32 bit bitfield, for which up to now 4 informational bits are defined, all unused bits have to be set to 0:

- `SANE_PFLAG_LAST_FRAME` (bit 0, bitvalue 1) is set to 1 if and only if the frame that is currently being acquired (or the frame that will be acquired next if there is no current frame) is the last frame of a multi frame image (e.g., the current frame is the blue component of a red, green, blue image). Note, that it is possible to transmit multiple images in succession.

- `SANE_PFLAG_MORE_IMAGES` (bit 1, bitvalue 2) is set to 1 to indicate further pending images. It is permissible to set that value to 1 "in good faith", as it has to be determined at a very early time, where it might not be detectable, if there actually are more images to transfer. E.g. you will usually not know if the document feeder contains further pages when starting to scan the current one. Thus you are allowed to set that bit but later fail at `sane_start()`.

- `SANE_PFLAG_NEW_PAGE` (bit 2, bitvalue 4) is set to 1 to indicate that the current frame comes from a new physical page. This bit is of informational character only to help frontends to group multi-image scans.

- `SANE_PFLAG_BACKSIDE` (bit 3, bitvalue 8) tells if the current image was acquired from the front (0) or backside (1) of the currently processed sheet. It is of informational character and allows to group and order multi-image transfers regardless of scanner acquisition order (front first/back first).

Note, that `flags` is compatible to member `last_frame` of `SANE_Parameters` of SANE standard version 1 (same size and only bit 0 (bitvalue 1) was used with same function).

Member `lines` specifies how many scan lines the frame is comprised of. If this value is -1, the number of lines is not known a priori and the frontend should call `sane_read()` until it returns a status of `SANE_STATUS_EOF`. Note, that even when transferring formats that have this information inband, it is recommended to set that member, if available. If unavailable or not applicable, set to -1 as mentioned above.

Member `bytes_per_line` specifies the number of bytes that comprise one scan line. If `bytes_per_line` is set to 0, which can currently only be the case for `SANE_FRAME_MIME`, the frontend shall not assume a constant line length. Instead it should simply try to read until `SANE_STATUS_EOF` with an arbitrary block length.

Member `depth` specifies the number of bits per sample. Note, that only 0 (for not applicable), 1, and n*8 are allowed values. Data with other depths has to be scaled up accordingly.

Member `pixels_per_line` specifies the number of pixels that comprise one scan line.

Assume B is the number of channels in the frame, then the bit depth d (as given by member `depth`) and the number of pixels per line n (as given by this member `pixels_per_line`) are related to c, the number of bytes per line (as given by member `bytes_per_line`) as follows:

c >= \left{ ll \lceil B*n / 8\rceil if d=1 (1)
B*n *\lceil (d + 7)/8 \rceil if d>1 \right.

Note that the number of bytes per line can be larger than the minimum value imposed by the right side of this equation. A frontend must be able to properly cope with such ``padded'' image formats.

Member `channels_per_image` specifies the number of channels the image consists of. When the image is transmitted in more than one frame `channels_per_image` has to be the same for all frames for this image.

Member `format_desc` is used for the new frametypes `SANE_FRAME_RAW` and `SANE_FRAME_MIME`. Its meaning differs between the two types:

- `SANE_FRAME_RAW`: The `format_desc` contains a description of the channel data and an optional depth information separated by a colon(:).

  A plane is descibed by one channel, e.g. "`gray`" or "`gray:12`".

  Channel interleaved data is described by a comma separated list of channel descriptions, for example "`red,green,blue`" or "`red:8,green:8,blue:8`", the channel data is sent in the given order.

  The depth information does not define the size of the transmitted channel data, it is only an information for the frontend. The channel data has to be sent in the size defined by member `depth`.

  Well known channels are `red`, `green`, `blue` and `gray`. It also is allowed to use other channel descriptions, e.g. if you use an infrared camera or scanner it could be `infrared` or a wavelength description like `1100nm`, but be aware that a frontend may not be able to display such channels with useful colors.

  Note that an image can be sent in single planes, in one interleaved frame that contains all channels or in several frames that contain one or more (interleaved) channels. When an RGB image is sent it is prefered to send the image data in one interleaved frame that consist of red, green and blue data in this order. The number of channels is defined in member `channels_per_image`.

- `SANE_FRAME_MIME`: The `format_desc` contains the MIME type/subtype *(;parameter) fields as described in RFC 1521, 4. The Content-Type header field, without the prefixing "Content-Type:". Note, that it is discouraged to transfer proprietary file formats over SANE. If at all possible, please stick to the IANA assigned MIME types, and make sure the data stream is compliant with the corresponding specification. When data is transmitted with the frame type `SANE_FRAME_MIME` all data has to be transmitted within one frame, multiple frames are not allowed (so the flag `last_frame` has to be set when using this frame type). A fully compliant SANE backend is required to transmit in either SANE native frametypes, or in a MIME type, for which a converting meta backend exists and is freely available for all platforms.

  Other formats may be transmitted, but the only thing the average frontend can do with them, is save them. This is not considered a good option, as it does not facilitate transmitting the data to a client application that may be running the frontend. However, if the data transferred by the backend is not an image in nature, it wouldn't make sense to try converting it anyway, so it is acceptable to use a simple `SANE_FRAME_MIME` transfer for that case. But even then, try to stick to well known stuff with freely existing standards and viewers as well.

The member `proposed_filename` can be used to suggest a reasonable default filename or -extension in case the backend can make such a suggestion, like e.g. an image database. If no such suggestion is intended, set the field to "".

In the case of raw frames, `proposed_filename` is expected to hold the basename for the image, with the extension determined by the save function of the frontend, as the frontend can fully understand the data and is thus able to encode it in any format it wishes.

For MIME frames `proposed_filename` can contain either:

- A name with a leading dot, which is considered to be a proposed filename extension. This could also be gotten from the mime database, but for systems lacking it, this might be convenient. Or:

- A complete filename, including extension.

Note, that for frontends that are able to parse a given MIME type internally, it is perfectly permissible to ignore the extension part of the proposed filename and only make use of the basename, when using internal save algorithms for different formats.

In any case, if the frontend makes use of this field, the frontend must mangle this proposal or the final filename it produces with its help to suit local filesystem restrictions.

Special care should be taken not to cause security flaws this way. For Unix, that means killing out all path separators (/) [to avoid to save away stuff in obscure places or create critical files like /etc/hosts.allow] and avoiding to overwrite existing files. (Creating of leading dot files - like .rhosts - is not an issue here, because that's only a proposed filename extension as mentioned above.

The string `proposed_comment` can be used to transmit additional image data, that can be stored in the comment areas several fileformats offer. It can contain any textual information the backend wishes to convey to the user, like date/time of exposure, enganged filters, etc.

The members `dpi_x, dpi_y` encode the horizontal and vertical resolution. Note, that multiple-image scans may have different resolutions of each image. It is not permissible to change resolution between frames of the same image.

The member `reserved` is an array of 32 bytes (char) to keep the size of the struct unchanged when future extensions are done. The backend has to set the reserved bytes to 0.

### 4.3.9 `sane_start`

This function initiates aquisition of an image from the device represented by handle `h`.

>     SANE_Status sane_start (SANE_Handle h);

This function may fail with one of the following status codes.

> `SANE_STATUS_CANCELLED`:
>   The operation was cancelled through a call to `sane_cancel`.
> `SANE_STATUS_DEVICE_BUSY`:
>   The device is busy. The operation should be retried later.
> `SANE_STATUS_JAMMED`:
>   The document feeder is jammed.
> `SANE_STATUS_NO_DOCS`:
>   The document feeder is out of documents.
> `SANE_STATUS_COVER_OPEN`:
>   The scanner cover is open.
> `SANE_STATUS_IO_ERROR`:
>   An error occurred while communicating with the device.
> `SANE_STATUS_NO_MEM`:
>   An insufficent amount of memory is available.
> `SANE_STATUS_INVAL`:
>   The scan cannot be started with the current set of options. The frontend should reload the option descriptors, as if `SANE_INFO_RELOAD_OPTIONS` had been returned from a call to `sane_control_option()`, since the device's capabilities may have changed.

### 4.3.10 `sane_read`

This function is used to read image data from the device represented by handle `h`. Argument `buf` is a pointer to a memory area that is at least `maxlen` bytes long. The number of bytes returned is stored in `*len`. A backend must set this to zero when a status other than `SANE_STATUS_GOOD` is returned). When the call succeeds, the number of bytes returned can be anywhere in the range from 0 to `maxlen` bytes.

>     SANE_Status sane_read (SANE_Handle h, SANE_Byte * buf,
>                            SANE_Int maxlen, SANE_Int * len);

For efficiency reasons, medium to large block sizes (in the range of a few kilobytes) should be used. Returning short reads is allowed to allow for small buffers in the backend. If this function is called when no data is available, one of two things may happen, depending on the I/O mode that is in effect for handle `h`.

1. If the device is in blocking I/O mode (the default mode), the call blocks until at least one data byte is available (or until some error occurs).

2. If the device is in non-blocking I/O mode, the call returns immediately with status `SANE_STATUS_GOOD` and with `*len` set to zero.

The I/O mode of handle `h` can be set via a call to `sane_set_io_mode()`.

This function may fail with one of the following status codes.

> `SANE_STATUS_CANCELLED`:
>   The operation was cancelled through a call to `sane_cancel`.
> `SANE_STATUS_EOF`:
>   No more data is available for the current frame. If `sane_read` sends back any image data it is not allowed to return with `SANE_STATUS_EOF`.
> `SANE_STATUS_JAMMED`:
>   The document feeder is jammed.
> `SANE_STATUS_NO_DOCS`:
>   The document feeder is out of documents.
> `SANE_STATUS_COVER_OPEN`:
>   The scanner cover is open.
> `SANE_STATUS_IO_ERROR`:
>   An error occurred while communicating with the device.
> `SANE_STATUS_NO_MEM`:
>   An insufficent amount of memory is available.
> `SANE_STATUS_ACCESS_DENIED`:
>   Access to the device has been denied due to insufficient or invalid authentication.

### 4.3.11 `sane_cancel`

This function is used to immediately or as quickly as possible cancel the currently pending operation of the device represented by handle `h`.

>     void sane_cancel (SANE_Handle h);

This function can be called at any time (as long as handle `h` is a valid handle) but usually affects long-running operations only (such as image is acquisition). It is safe to call this function asynchronously (e.g., from within a signal handler). It is important to note that completion of this operaton does not imply that the currently pending operation has been cancelled. It only guarantees that cancellation has been initiated. Cancellation completes only when the cancelled call returns (typically with a status value of `SANE_STATUS_CANCELLED`). Since the SANE API does not require any other operations to be re-entrant, this implies that a frontend must not call any other operation until the cancelled operation has returned.

### 4.3.12 `sane_set_io_mode`

This function is used to set the I/O mode of handle `h`. The I/O mode can be either blocking or non-blocking. If argument `m` is `SANE_TRUE`, the mode is set to non-blocking mode, otherwise it's set to blocking mode. This function can be called only after a call to `sane_start()` has been performed.

>     SANE_Status sane_set_io_mode (SANE_Handle h, SANE_Bool m);

By default, newly opened handles operate in blocking mode. A backend may elect not to support non-blocking I/O mode. In such a case the status value `SANE_STATUS_UNSUPPORTED` is returned. Blocking I/O must be supported by all backends, so calling this function with argument `m` set to `SANE_FALSE` is guaranteed to complete successfully.

This function may fail with one of the following status codes:

> `SANE_STATUS_INVAL`:
>   No image acquisition is pending.
> `SANE_STATUS_UNSUPPORTED`:
>   The backend does not support the requested I/O mode.

### 4.3.13 `sane_get_select_fd`

This function is used to obtain a (platform-specific) file-descriptor for handle `h` that is readable if and only if image data is available (i.e., when a call to `sane_read()` will return at least one byte of data). If the call completes successfully, the select file-descriptor is returned in `*fd`.

>     SANE_Status sane_get_select_fd (SANE_Handle h, SANE_Int *fd);

This function can be called only after a call to `sane_start()` has been performed and the returned file-descriptor is guaranteed to remain valid for the duration of the current image acquisition (i.e., until `sane_cancel()` or `sane_start()` get called again or until `sane_read()` returns with status `SANE_STATUS_EOF`). Indeed, a backend must guarantee to close the returned select file descriptor at the point when the next `sane_read()` call would return `SANE_STATUS_EOF`. This is necessary to ensure the application can detect when this condition occurs without actually having to call `sane_read()`.

A backend may elect not to support this operation. In such a case, the function returns with status code `SANE_STATUS_UNSUPPORTED`.

Note that the only operation supported by the returned file-descriptor is a host operating-system dependent test whether the file-descriptor is readable (e.g., this test can be implemented using `select()` or `poll()` under UNIX). If any other operation is performed on the file descriptor, the behavior of the backend becomes unpredictable. Once the file-descriptor signals ``readable'' status, it will remain in that state until a call to `sane_read()` is performed. Since many input devices are very slow, support for this operation is strongly encouraged as it permits an application to do other work while image acquisition is in progress.

This function may fail with one of the following status codes:

> `SANE_STATUS_INVAL`:
>   No image acquisition is pending.
> `SANE_STATUS_UNSUPPORTED`:
>   The backend does not support this operation.

### 4.3.14 `sane_strstatus`

This function can be used to translate a SANE status code into a printable string. The returned string is a single line of text that forms a complete sentence, but without the trailing period (full-stop). The function is guaranteed to never return `NULL`. The returned pointer is valid at least until the next call to this function is performed.

>     const SANE_String_Const sane_strstatus (SANE_Status status);