#!/usr/bin/python3
"""Selfie: live preview of the N900 cameras (front by default) and a photo button. Python 3 + hildonlite + GStreamer 0.10 (camerabin) through ctypes.
Test application for the cameras: /dev/video1 = front (VGA, vs6555), /dev/video0 = back (et8ek8).
Environment: SELFIE_SINK (default xvimagesink), SELFIE_DRIVER (camera driver module of v4l2camsrc), SELFIE_BUTTON (see below), SELFIE_TIMEOUT (seconds, quit by itself).
The hardware camera button (half press, the full press belongs to the stock Camera) takes a photo as well.
Photos: ~/MyDocs/DCIM/selfie-YYYYMMDD-HHMMSS.jpg."""
import ctypes, os, sys, time
sys.path.insert(0, "/opt/python3/lib/python3.11/site-packages")      # hildonlite (package python3-hildonlite)
try:
    import hildonlite as hl
except ImportError:                                                   # development tree: apps/hildonlite next to this app
    sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "hildonlite"))
    import hildonlite as hl

CAMERAS = [("Front camera", "/dev/video1", (640, 480)), ("Back camera", "/dev/video0", (2592, 1968))]       # name, device, photo size
DRIVER = os.environ.get("SELFIE_DRIVER", "libomap3cam.so.0")
SINK = os.environ.get("SELFIE_SINK", "xvimagesink")
ICONS = os.path.join(os.path.dirname(os.path.realpath(__file__)), "icons")          # /opt/selfie/icons, in the source tree apps/selfie/icons
PHOTO_DIR = os.path.expanduser("~/MyDocs/DCIM")
NULL, READY, PLAYING = 1, 2, 4
# The hardware camera button is not an input device: the kernel exposes it as GPIO switches (cam_focus = half press, cam_launch = full press,
# cam_shutter = lens cover). The state files are readable by every user and say "active" / "inactive".
SWITCHES = "/sys/devices/platform/gpio-switch"
# The full press (cam_launch) starts the stock Camera application (the system reacts to it before us), so the HALF press (cam_focus) is the shutter here.
# SELFIE_BUTTON=cam_launch / none changes it (none: only the on-screen button).
BUTTON = os.environ.get("SELFIE_BUTTON", "cam_focus")


def switch_active(name):
    try:
        with open("%s/%s/state" % (SWITCHES, name)) as f:
            return f.read().strip() == "active"
    except OSError:
        return False            # no such switch (emulator): the button never fires


class Camera:
    """GStreamer 0.10 camerabin through ctypes: viewfinder drawn into an X window, still capture (signal user-start) without stopping the viewfinder.
    camerabin is what the stock Camera uses: with the driver module libomap3cam (property driver-name of v4l2camsrc) the sensor gets automatic
    exposure and white balance; the plain v4l2src gives raw, dark pictures with a colour cast. Capture runs asynchronously: img-done is queued
    in self.done (the callback may come from a GStreamer thread) and read by the main loop."""

    def __init__(self):
        self.gst = ctypes.CDLL("libgstreamer-0.10.so.0")
        self.gif = ctypes.CDLL("libgstinterfaces-0.10.so.0")
        self.gobj = ctypes.CDLL("libgobject-2.0.so.0")
        g, o = self.gst, self.gobj
        g.gst_element_factory_make.restype = ctypes.c_void_p
        g.gst_element_factory_make.argtypes = [ctypes.c_char_p, ctypes.c_char_p]
        g.gst_element_set_state.argtypes = [ctypes.c_void_p, ctypes.c_int]
        g.gst_element_get_state.argtypes = [ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_uint64]
        g.gst_object_unref.argtypes = [ctypes.c_void_p]
        self.gif.gst_x_overlay_set_xwindow_id.argtypes = [ctypes.c_void_p, ctypes.c_ulong]
        o.g_object_set.restype = None
        o.g_signal_connect_data.restype = ctypes.c_ulong
        o.g_signal_emit_by_name.restype = None
        g.gst_init(None, None)
        self.cb = None
        self.done = []
        self._img_done = ctypes.CFUNCTYPE(ctypes.c_int, ctypes.c_void_p, ctypes.c_char_p, ctypes.c_void_p)(self._on_img_done)

    def _on_img_done(self, _cb, filename, _data):
        self.done.append(filename.decode("utf-8", "replace") if filename else "")
        return 0                                  # FALSE: no further handling

    def start(self, device, xid, size):
        """Start the viewfinder of `device` in the X window xid; `size` = (width, height) of the photos. Returns an error text or None."""
        self.stop()
        g, o = self.gst, self.gobj
        cb = g.gst_element_factory_make(b"camerabin", b"cb")
        src = g.gst_element_factory_make(b"v4l2camsrc", b"src")
        sink = g.gst_element_factory_make(SINK.encode(), b"vf")
        if not (cb and src and sink):
            return "GStreamer elements missing (camerabin, v4l2camsrc, %s)" % SINK
        o.g_object_set(src, b"device", device.encode(), None)
        o.g_object_set(src, b"driver-name", DRIVER.encode(), None)
        o.g_object_set(cb, b"videosrc", ctypes.c_void_p(src), None)
        o.g_object_set(cb, b"vfsink", ctypes.c_void_p(sink), None)
        o.g_object_set(cb, b"mode", ctypes.c_int(0), None)                    # still images
        o.g_signal_connect_data(ctypes.c_void_p(cb), b"img-done", self._img_done, None, None, 0)
        self.gif.gst_x_overlay_set_xwindow_id(sink, xid)
        g.gst_element_set_state(cb, PLAYING)
        state = ctypes.c_int()
        if g.gst_element_get_state(cb, ctypes.byref(state), None, 4 * 10**9) == 0:      # GST_STATE_CHANGE_FAILURE
            g.gst_element_set_state(cb, NULL)
            g.gst_object_unref(cb)
            return "the camera does not start (is another program using it?)"
        self.cb = cb
        self.size = size
        return None

    def capture(self, path):
        """Take a picture into `path` (returns at once; the file name shows up in self.done when the JPEG is written)."""
        o = self.gobj
        o.g_object_set(self.cb, b"filename", path.encode(), None)
        o.g_signal_emit_by_name(ctypes.c_void_p(self.cb), b"user-image-res", ctypes.c_int(self.size[0]), ctypes.c_int(self.size[1]))
        o.g_signal_emit_by_name(ctypes.c_void_p(self.cb), b"user-start")

    def stop(self):
        if self.cb:
            self.gst.gst_element_set_state(self.cb, NULL)
            self.gst.gst_object_unref(self.cb)
            self.cb = None


def main():
    if not hl.init():
        sys.exit("no X display")
    try:
        cam = Camera()
    except OSError:                                              # no GStreamer (the emulator): the window still opens
        cam = None
    state = {"camera": 0, "busy": 0}
    win = hl.Window("Selfie")
    row = hl.HBox(spacing=8)
    view = hl.DrawingArea(640, 420)
    row.add(view, expand=True)
    side = hl.VBox(spacing=8)
    status = hl.Label("", wrap=True)

    def start_preview():
        name, device, size = CAMERAS[state["camera"]]
        if cam is None:
            status.set_text("no GStreamer")
            return
        err = cam.start(device, view.xid(), size)
        status.set_text(err or name)

    def photo(_b):
        if cam is None or cam.cb is None or state["busy"]:
            return
        os.makedirs(PHOTO_DIR, exist_ok=True)
        state["busy"] = 1
        status.set_text("Saving...")
        cam.capture(os.path.join(PHOTO_DIR, time.strftime("selfie-%Y%m%d-%H%M%S.jpg")))

    def switch(_b):
        state["camera"] = (state["camera"] + 1) % len(CAMERAS)
        start_preview()

    # the camera button: the half press takes a photo; polled 10 times a second, only the edge inactive -> active counts.
    # The same timer reports finished captures (the viewfinder goes on while the JPEG is written).
    button = {"was": switch_active(BUTTON)}

    def poll():
        now = switch_active(BUTTON)
        if now and not button["was"]:
            photo(None)
        button["was"] = now
        while cam is not None and cam.done:
            path = cam.done.pop(0)
            state["busy"] = 0
            status.set_text(CAMERAS[state["camera"]][0])
            hl.Banner(win, "Saved: " + os.path.basename(path))
        return True

    hl.timeout(100, poll)
    icon = lambda n: os.path.join(ICONS, "ui-%s.png" % n)
    side.add(hl.ImageButton(icon("shutter"), photo, width=84, label="Photo"))          # also: half press of the camera button
    side.add(hl.ImageButton(icon("switch"), switch, width=84, label="Cam"))
    side.add(hl.ImageButton(icon("close"), lambda b: hl.quit(), width=84, label="X"))
    side.add(status, expand=True)
    row.add(side)
    win.add(row)
    win.show()
    hl.timeout(300, lambda: (start_preview(), False)[1])        # after the window is mapped
    if os.environ.get("SELFIE_TIMEOUT"):
        hl.timeout(int(os.environ["SELFIE_TIMEOUT"]) * 1000, lambda: hl.quit() or False)
    hl.main()
    if cam:
        cam.stop()


if __name__ == "__main__":
    main()
