1 import ./make-test-python.nix ({ pkgs, ... }:
5 SANE is intrisically tied to hardware, so testing it is not straightforward.
7 - a fake webcam can be created with v4l2loopback
8 - sane has a backend (v4l) to use a webcam as a scanner
9 This test creates a webcam /dev/video0, streams a still image with some text
10 through this webcam, uses SANE to scan from the webcam, and uses OCR to check
11 that the expected text was scanned.
14 text = "66263666188646651519653683416";
15 fontsConf = pkgs.makeFontsConf {
17 pkgs.dejavu_fonts.minimal
20 # an image with black on white text spelling "${text}"
21 # for some reason, the test fails if it's jpg instead of png
22 # the font is quite large to make OCR easier
23 image = pkgs.runCommand "image.png"
25 # only imagemagickBig can render text
26 nativeBuildInputs = [ pkgs.imagemagickBig ];
27 FONTCONFIG_FILE = fontsConf;
29 magick -pointsize 100 label:${text} $out
34 nodes.machine = { pkgs, config, ... }: {
36 # create /dev/video0 as a fake webcam whose content is filled by ffmpeg
37 extraModprobeConfig = ''
38 options v4l2loopback devices=1 max_buffers=2 exclusive_caps=1 card_label=VirtualCam
40 kernelModules = [ "v4l2loopback" ];
41 extraModulePackages = [ config.boot.kernelPackages.v4l2loopback ];
43 systemd.services.fake-webcam = {
44 wantedBy = [ "multi-user.target" ];
45 description = "fill /dev/video0 with ${image}";
46 /* HACK: /dev/video0 is a v4l2 only device, it misses one single v4l1
47 ioctl, VIDIOCSPICT. But sane only supports v4l1, so it will log that this
48 ioctl failed, and assume that the pixel format is Y8 (gray). So we tell
49 ffmpeg to produce this pixel format.
51 serviceConfig.ExecStart = [ "${pkgs.ffmpeg}/bin/ffmpeg -framerate 30 -re -stream_loop -1 -i ${image} -f v4l2 -pix_fmt gray /dev/video0" ];
53 hardware.sane.enable = true;
54 system.extraDependencies = [ image ];
55 environment.systemPackages = [
60 environment.variables.SANE_DEBUG_V4L = "128";
64 machine.wait_for_unit("fake-webcam.service")
66 # the device only appears when ffmpeg starts producing frames
67 machine.wait_until_succeeds("scanimage -L | grep /dev/video0")
69 machine.succeed("scanimage -L >&2")
71 with subtest("debugging: /dev/video0 works"):
72 machine.succeed("v4l2-ctl --all >&2")
73 machine.succeed("fswebcam --no-banner /tmp/webcam.jpg")
74 machine.copy_from_vm("/tmp/webcam.jpg", "webcam")
76 # scan with the webcam
77 machine.succeed("scanimage -o /tmp/scan.png >&2")
78 machine.copy_from_vm("/tmp/scan.png", "scan")
80 # the image should contain "${text}"
81 output = machine.succeed("tesseract /tmp/scan.png -")
83 assert "${text}" in output, f"expected text ${text} was not found, OCR found {output!r}"