File size: 3,525 Bytes
2a2a176
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
"""The Java process: ZXing as Android's Settings app calls it (see reading.py). One process, shared by every reading,
reads the staged frames one at a time; it is replaced when it dies or a frame runs past TIMEOUT_S.
"""

from __future__ import annotations

import base64
import itertools
import json
import os
import queue
import subprocess
import threading
import time

from .reading_rules import TIMEOUT_S, VENDOR


class _Java:
    def __init__(self):
        cp = os.pathsep.join([str(VENDOR / "zxing" / "core-3.5.2.jar"), str(VENDOR / "zxing" / "classes")])
        self.cmd = ["java", "-Djava.awt.headless=true", "-Xmx512m", "-cp", cp, "ZxingServer"]
        self.lock = threading.Lock()
        self.ids = itertools.count()
        self._spawn()

    def _spawn(self) -> None:
        self.proc = subprocess.Popen(self.cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
                                     stderr=subprocess.DEVNULL, text=True, encoding="utf-8", bufsize=1)
        self.lines: queue.Queue = queue.Queue()
        threading.Thread(target=self._pump, args=(self.proc.stdout, self.lines), daemon=True).start()

    @staticmethod
    def _pump(stream, lines: queue.Queue) -> None:
        for line in stream:
            lines.put(line)
        lines.put(None)

    def close(self) -> None:
        self.proc.kill()
        self.proc.wait(5)
        try:
            self.proc.stdin.close()
        except OSError:   # its pipe broke with it
            pass

    def read(self, paths: list[str], deadline: float) -> list[list[bytes] | None]:
        """Per frame, ZXing's contents (empty: no read, a timeout included); None where the deadline left it unread."""
        out: list[list[bytes] | None] = [None] * len(paths)
        deaths = 0
        for k, p in enumerate(paths):
            # one frame at a time, so two pictures read at once take turns; never waiting past this one's deadline
            if not self.lock.acquire(timeout=max(0.0, deadline - time.monotonic())):
                break
            try:
                left = deadline - time.monotonic()
                if left <= 0:
                    break
                if self.proc.poll() is not None:   # it died since its last answer (while idle): not a miss
                    self.close()
                    self._spawn()
                rid = next(self.ids)
                obj, died = None, False
                try:
                    self.proc.stdin.write(f"{rid}\t{p}\n")
                    self.proc.stdin.flush()
                    line = self.lines.get(timeout=min(TIMEOUT_S, left))
                    died = line is None   # its output ended: it exited without answering
                    obj = json.loads(line) if line else None
                except OSError:   # its pipe broke: it exited
                    died = True
                except (ValueError, queue.Empty):
                    pass
                if not isinstance(obj, dict) or obj.get("id") != rid:   # a timeout, a crash or a stray line: a miss
                    self.close()
                    self._spawn()
                    deaths += died
                    if deaths > 1:   # it keeps dying: this frame and the rest are unread, not misses
                        break
                    out[k] = [] if time.monotonic() < deadline else None
                    continue
                out[k] = [base64.b64decode(c) for c in obj.get("contents", [])]
            finally:
                self.lock.release()
        return out