1{ pkgs, ... }:
2/*
3 SANE NixOS test
4 ===============
5 SANE is intrisically tied to hardware, so testing it is not straightforward.
6 However:
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.
12*/
13let
14 text = "66263666188646651519653683416";
15 fontsConf = pkgs.makeFontsConf {
16 fontDirectories = [
17 pkgs.dejavu_fonts.minimal
18 ];
19 };
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 =
24 pkgs.runCommand "image.png"
25 {
26 # only imagemagickBig can render text
27 nativeBuildInputs = [ pkgs.imagemagickBig ];
28 FONTCONFIG_FILE = fontsConf;
29 }
30 ''
31 magick -pointsize 100 label:${text} $out
32 '';
33in
34{
35 name = "sane";
36 nodes.machine =
37 { pkgs, config, ... }:
38 {
39 boot = {
40 # create /dev/video0 as a fake webcam whose content is filled by ffmpeg
41 extraModprobeConfig = ''
42 options v4l2loopback devices=1 max_buffers=2 exclusive_caps=1 card_label=VirtualCam
43 '';
44 kernelModules = [ "v4l2loopback" ];
45 extraModulePackages = [ config.boot.kernelPackages.v4l2loopback ];
46 };
47 systemd.services.fake-webcam = {
48 wantedBy = [ "multi-user.target" ];
49 description = "fill /dev/video0 with ${image}";
50 /*
51 HACK: /dev/video0 is a v4l2 only device, it misses one single v4l1
52 ioctl, VIDIOCSPICT. But sane only supports v4l1, so it will log that this
53 ioctl failed, and assume that the pixel format is Y8 (gray). So we tell
54 ffmpeg to produce this pixel format.
55 */
56 serviceConfig.ExecStart = [
57 "${pkgs.ffmpeg}/bin/ffmpeg -framerate 30 -re -stream_loop -1 -i ${image} -f v4l2 -pix_fmt gray /dev/video0"
58 ];
59 };
60 hardware.sane.enable = true;
61 system.extraDependencies = [ image ];
62 environment.systemPackages = [
63 pkgs.fswebcam
64 pkgs.tesseract
65 pkgs.v4l-utils
66 ];
67 environment.variables.SANE_DEBUG_V4L = "128";
68 };
69 testScript = ''
70 start_all()
71 machine.wait_for_unit("fake-webcam.service")
72
73 # the device only appears when ffmpeg starts producing frames
74 machine.wait_until_succeeds("scanimage -L | grep /dev/video0")
75
76 machine.succeed("scanimage -L >&2")
77
78 with subtest("debugging: /dev/video0 works"):
79 machine.succeed("v4l2-ctl --all >&2")
80 machine.succeed("fswebcam --no-banner /tmp/webcam.jpg")
81 machine.copy_from_vm("/tmp/webcam.jpg", "webcam")
82
83 # scan with the webcam
84 machine.succeed("scanimage -o /tmp/scan.png >&2")
85 machine.copy_from_vm("/tmp/scan.png", "scan")
86
87 # the image should contain "${text}"
88 output = machine.succeed("tesseract /tmp/scan.png -")
89 print(output)
90 assert "${text}" in output, f"expected text ${text} was not found, OCR found {output!r}"
91 '';
92}