{"id":16122,"url":"https://patchwork.libcamera.org/api/patches/16122/?format=json","web_url":"https://patchwork.libcamera.org/patch/16122/","project":{"id":1,"url":"https://patchwork.libcamera.org/api/projects/1/?format=json","name":"libcamera","link_name":"libcamera","list_id":"libcamera_core","list_email":"libcamera-devel@lists.libcamera.org","web_url":"","scm_url":"","webscm_url":""},"msgid":"<20220530142722.57618-16-tomi.valkeinen@ideasonboard.com>","date":"2022-05-30T14:27:21","name":"[libcamera-devel,v4,15/16] py: examples: Add itest.py","commit_ref":null,"pull_url":null,"state":"superseded","archived":false,"hash":"58a505da8ff175a7b2987eddb587715a9cbc772c","submitter":{"id":109,"url":"https://patchwork.libcamera.org/api/people/109/?format=json","name":"Tomi Valkeinen","email":"tomi.valkeinen@ideasonboard.com"},"delegate":null,"mbox":"https://patchwork.libcamera.org/patch/16122/mbox/","series":[{"id":3149,"url":"https://patchwork.libcamera.org/api/series/3149/?format=json","web_url":"https://patchwork.libcamera.org/project/libcamera/list/?series=3149","date":"2022-05-30T14:27:06","name":"More misc Python patches","version":4,"mbox":"https://patchwork.libcamera.org/series/3149/mbox/"}],"comments":"https://patchwork.libcamera.org/api/patches/16122/comments/","check":"pending","checks":"https://patchwork.libcamera.org/api/patches/16122/checks/","tags":{},"headers":{"Return-Path":"<libcamera-devel-bounces@lists.libcamera.org>","X-Original-To":"parsemail@patchwork.libcamera.org","Delivered-To":"parsemail@patchwork.libcamera.org","Received":["from lancelot.ideasonboard.com (lancelot.ideasonboard.com\n\t[92.243.16.209])\n\tby patchwork.libcamera.org (Postfix) with ESMTPS id 28816C3279\n\tfor <parsemail@patchwork.libcamera.org>;\n\tMon, 30 May 2022 14:27:56 +0000 (UTC)","from lancelot.ideasonboard.com (localhost [IPv6:::1])\n\tby lancelot.ideasonboard.com (Postfix) with ESMTP id 885B165699;\n\tMon, 30 May 2022 16:27:55 +0200 (CEST)","from perceval.ideasonboard.com (perceval.ideasonboard.com\n\t[IPv6:2001:4b98:dc2:55:216:3eff:fef7:d647])\n\tby lancelot.ideasonboard.com (Postfix) with ESMTPS id EEC6A6563B\n\tfor <libcamera-devel@lists.libcamera.org>;\n\tMon, 30 May 2022 16:27:46 +0200 (CEST)","from deskari.lan (91-156-85-209.elisa-laajakaista.fi\n\t[91.156.85.209])\n\tby perceval.ideasonboard.com (Postfix) with ESMTPSA id 604581918;\n\tMon, 30 May 2022 16:27:46 +0200 (CEST)"],"DKIM-Signature":["v=1; a=rsa-sha256; c=relaxed/simple; d=libcamera.org;\n\ts=mail; t=1653920875;\n\tbh=Dqbd2jWSxJoWb7CMOMAO8z/GpiNtZdD+FqW7WPAxi3c=;\n\th=To:Date:In-Reply-To:References:Subject:List-Id:List-Unsubscribe:\n\tList-Archive:List-Post:List-Help:List-Subscribe:From:Reply-To:\n\tFrom;\n\tb=z6wK3r1yOvuxvFG+OD61SWygsGLvERHnTa57flEUnlRLzlRA5O6bx/wGCof29i2jH\n\tmaYBRMpTftLnD0zS0K5g7gvLDMePPLv9cmLdepaPSdSa47juFTcWL6t7cZ83tEwMnd\n\tDGXLGX402+nW1NBZawUsQ8YunrRLRzjbtJIbAM+W9A9RdzKkkC7atcFH3tLoJLIleI\n\tZGwRQnFO5gZe0JEZ/Sau/KZyseA+FYyHKpSnQ5oAtNCDh4hmA/e2gB/HQYPYE/yxPf\n\thOYmK4hJVMjXxkD92snqhjNN0U4Tek5EXQs5gjSYhN6pyKqKy92kEaoz0T/GiTPa4d\n\tSNBE/Ia33M7vA==","v=1; a=rsa-sha256; c=relaxed/simple; d=ideasonboard.com;\n\ts=mail; t=1653920866;\n\tbh=Dqbd2jWSxJoWb7CMOMAO8z/GpiNtZdD+FqW7WPAxi3c=;\n\th=From:To:Cc:Subject:Date:In-Reply-To:References:From;\n\tb=hV2abj3xlK2uHgBShu00YOf06XVwNySpnMh63NQg7Ya73HPm+i75QsNy75s8S0UHY\n\tumyM9C3BvEZpQDkCAi/zpwqzx+EHpKUuMsVKFXZeKZ4cZWaEetllAjIaSF5r6th4+R\n\tbxudVSPvaR20DP02aNDx1oA6sjhsDn7QYg/6nbSo="],"Authentication-Results":"lancelot.ideasonboard.com; dkim=pass (1024-bit key; \n\tunprotected) header.d=ideasonboard.com\n\theader.i=@ideasonboard.com\n\theader.b=\"hV2abj3x\"; dkim-atps=neutral","To":"libcamera-devel@lists.libcamera.org,\n\tDavid Plowman <david.plowman@raspberrypi.com>,\n\tKieran Bingham <kieran.bingham@ideasonboard.com>,\n\tLaurent Pinchart <laurent.pinchart@ideasonboard.com>,\n\tJacopo Mondi <jacopo@jmondi.org>","Date":"Mon, 30 May 2022 17:27:21 +0300","Message-Id":"<20220530142722.57618-16-tomi.valkeinen@ideasonboard.com>","X-Mailer":"git-send-email 2.34.1","In-Reply-To":"<20220530142722.57618-1-tomi.valkeinen@ideasonboard.com>","References":"<20220530142722.57618-1-tomi.valkeinen@ideasonboard.com>","MIME-Version":"1.0","Content-Transfer-Encoding":"8bit","Subject":"[libcamera-devel] [PATCH v4 15/16] py: examples: Add itest.py","X-BeenThere":"libcamera-devel@lists.libcamera.org","X-Mailman-Version":"2.1.29","Precedence":"list","List-Id":"<libcamera-devel.lists.libcamera.org>","List-Unsubscribe":"<https://lists.libcamera.org/options/libcamera-devel>,\n\t<mailto:libcamera-devel-request@lists.libcamera.org?subject=unsubscribe>","List-Archive":"<https://lists.libcamera.org/pipermail/libcamera-devel/>","List-Post":"<mailto:libcamera-devel@lists.libcamera.org>","List-Help":"<mailto:libcamera-devel-request@lists.libcamera.org?subject=help>","List-Subscribe":"<https://lists.libcamera.org/listinfo/libcamera-devel>,\n\t<mailto:libcamera-devel-request@lists.libcamera.org?subject=subscribe>","From":"Tomi Valkeinen via libcamera-devel\n\t<libcamera-devel@lists.libcamera.org>","Reply-To":"Tomi Valkeinen <tomi.valkeinen@ideasonboard.com>","Errors-To":"libcamera-devel-bounces@lists.libcamera.org","Sender":"\"libcamera-devel\" <libcamera-devel-bounces@lists.libcamera.org>"},"content":"Add a small tool which gives the user an IPython based interactive shell\nwith libcamera capturing in the background. Can be used to study and\ntest small things with libcamera.\n\nSigned-off-by: Tomi Valkeinen <tomi.valkeinen@ideasonboard.com>\n---\n src/py/examples/itest.py | 195 +++++++++++++++++++++++++++++++++++++++\n 1 file changed, 195 insertions(+)\n create mode 100755 src/py/examples/itest.py","diff":"diff --git a/src/py/examples/itest.py b/src/py/examples/itest.py\nnew file mode 100755\nindex 00000000..9c97649d\n--- /dev/null\n+++ b/src/py/examples/itest.py\n@@ -0,0 +1,195 @@\n+#!/usr/bin/env python3\n+\n+# SPDX-License-Identifier: BSD-3-Clause\n+# Copyright (C) 2022, Tomi Valkeinen <tomi.valkeinen@ideasonboard.com>\n+\n+# This sets up a single camera, starts a capture loop in a background thread,\n+# and starts an IPython shell which can be used to study and test libcamera.\n+#\n+# Note: This is not an example as such, but more of a developer tool to try\n+# out things.\n+\n+import argparse\n+import IPython\n+import libcamera as libcam\n+import selectors\n+import sys\n+import threading\n+\n+\n+def handle_camera_event(ctx):\n+    cm = ctx['cm']\n+    cam = ctx['cam']\n+\n+    # cm.get_ready_requests() will not block here, as we know there is an event\n+    # to read.\n+\n+    reqs = cm.get_ready_requests()\n+\n+    assert len(reqs) > 0\n+\n+    # Process the captured frames\n+\n+    for req in reqs:\n+        buffers = req.buffers\n+\n+        assert len(buffers) == 1\n+\n+        # We want to re-queue the buffer we just handled. Instead of creating\n+        # a new Request, we re-use the old one. We need to call req.reuse()\n+        # to re-initialize the Request before queuing.\n+\n+        req.reuse()\n+        cam.queue_request(req)\n+\n+        scope = ctx['scope']\n+\n+        if 'num_frames' not in scope:\n+            scope['num_frames'] = 0\n+\n+        scope['num_frames'] += 1\n+\n+\n+def capture(ctx):\n+    cm = ctx['cm']\n+    cam = ctx['cam']\n+    reqs = ctx['reqs']\n+\n+    # Queue the requests to the camera\n+\n+    for req in reqs:\n+        ret = cam.queue_request(req)\n+        assert ret == 0\n+\n+    # Use Selector to wait for events from the camera and from the keyboard\n+\n+    sel = selectors.DefaultSelector()\n+    sel.register(cm.event_fd, selectors.EVENT_READ, lambda fd: handle_camera_event(ctx))\n+\n+    reqs = []\n+\n+    while ctx['running']:\n+        events = sel.select()\n+        for key, mask in events:\n+            key.data(key.fileobj)\n+\n+\n+def main():\n+    parser = argparse.ArgumentParser()\n+    parser.add_argument('-c', '--camera', type=str, default='1',\n+                        help='Camera index number (starting from 1) or part of the name')\n+    parser.add_argument('-f', '--format', type=str, help='Pixel format')\n+    parser.add_argument('-s', '--size', type=str, help='Size (\"WxH\")')\n+    args = parser.parse_args()\n+\n+    cm = libcam.CameraManager.singleton()\n+\n+    try:\n+        if args.camera.isnumeric():\n+            cam_idx = int(args.camera)\n+            cam = next((cam for i, cam in enumerate(cm.cameras) if i + 1 == cam_idx))\n+        else:\n+            cam = next((cam for cam in cm.cameras if args.camera in cam.id))\n+    except Exception:\n+        print(f'Failed to find camera \"{args.camera}\"')\n+        return -1\n+\n+    # Acquire the camera for our use\n+\n+    ret = cam.acquire()\n+    assert ret == 0\n+\n+    # Configure the camera\n+\n+    cam_config = cam.generate_configuration([libcam.StreamRole.Viewfinder])\n+\n+    stream_config = cam_config.at(0)\n+\n+    if args.format:\n+        fmt = libcam.PixelFormat(args.format)\n+        stream_config.pixel_format = fmt\n+\n+    if args.size:\n+        w, h = [int(v) for v in args.size.split('x')]\n+        stream_config.size = libcam.Size(w, h)\n+\n+    ret = cam.configure(cam_config)\n+    assert ret == 0\n+\n+    stream = stream_config.stream\n+\n+    # Allocate the buffers for capture\n+\n+    allocator = libcam.FrameBufferAllocator(cam)\n+    ret = allocator.allocate(stream)\n+    assert ret > 0\n+\n+    num_bufs = len(allocator.buffers(stream))\n+\n+    print(f'Capturing {stream_config} with {num_bufs} buffers from {cam.id}')\n+\n+    # Create the requests and assign a buffer for each request\n+\n+    reqs = []\n+    for i in range(num_bufs):\n+        # Use the buffer index as the \"cookie\"\n+        req = cam.create_request(i)\n+\n+        buffer = allocator.buffers(stream)[i]\n+        ret = req.add_buffer(stream, buffer)\n+        assert ret == 0\n+\n+        reqs.append(req)\n+\n+    # Start the camera\n+\n+    ret = cam.start()\n+    assert ret == 0\n+\n+    # Create a scope for the IPython shell\n+    scope = {\n+        'cm': cm,\n+        'cam': cam,\n+        'libcam': libcam,\n+    }\n+\n+    # Create a simple context shared between the background thread and the main\n+    # thread.\n+    ctx = {\n+        'running': True,\n+        'cm': cm,\n+        'cam': cam,\n+        'reqs': reqs,\n+        'scope': scope,\n+    }\n+\n+    # Note that \"In CPython, due to the Global Interpreter Lock, only one thread\n+    # can execute Python code at once\". We rely on that here, which is not very\n+    # nice. I am sure an fd-based polling loop could be integrated with IPython,\n+    # somehow, which would allow us to drop the threading.\n+\n+    t = threading.Thread(target=capture, args=(ctx,))\n+    t.start()\n+\n+    IPython.embed(banner1='', exit_msg='', confirm_exit=False, user_ns=scope)\n+\n+    print('Exiting...')\n+\n+    ctx['running'] = False\n+    t.join()\n+\n+    # Stop the camera\n+\n+    ret = cam.stop()\n+    assert ret == 0\n+\n+    # Release the camera\n+\n+    ret = cam.release()\n+    assert ret == 0\n+\n+    return 0\n+\n+\n+if __name__ == '__main__':\n+    sys.exit(main())\n","prefixes":["libcamera-devel","v4","15/16"]}