[{"id":23167,"web_url":"https://patchwork.libcamera.org/comment/23167/","msgid":"<Yo+ntcrv4vTae9NK@pendragon.ideasonboard.com>","date":"2022-05-26T16:15:49","subject":"Re: [libcamera-devel] [PATCH v2 12/19] py: examples: Add itest.py","submitter":{"id":2,"url":"https://patchwork.libcamera.org/api/people/2/","name":"Laurent Pinchart","email":"laurent.pinchart@ideasonboard.com"},"content":"Hi Tomi,\n\nThank you for the patch.\n\nOn Tue, May 24, 2022 at 02:46:03PM +0300, Tomi Valkeinen wrote:\n> Add a small tool which gives the user an IPython based interactive shell\n> with libcamera capturing in the background. Can be used to study and\n> test small things with libcamera.\n\nInteresting.\n\nCan I let you update this in a v3 to take comments from other patches\ninto account, and review it then ?\n\n> Signed-off-by: Tomi Valkeinen <tomi.valkeinen@ideasonboard.com>\n> ---\n>  src/py/examples/itest.py | 197 +++++++++++++++++++++++++++++++++++++++\n>  1 file changed, 197 insertions(+)\n>  create mode 100755 src/py/examples/itest.py\n> \n> diff --git a/src/py/examples/itest.py b/src/py/examples/itest.py\n> new file mode 100755\n> index 00000000..01e020e2\n> --- /dev/null\n> +++ b/src/py/examples/itest.py\n> @@ -0,0 +1,197 @@\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.read_event() will not block here, as we know there is an event to read.\n> +    # We have to read the event to clear it.\n> +\n> +    cm.read_event()\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.efd, 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> +    camconfig = cam.generate_configuration([libcam.StreamRole.StillCapture])\n> +\n> +    streamconfig = camconfig.at(0)\n> +\n> +    if args.format:\n> +        fmt = libcam.PixelFormat(args.format)\n> +        streamconfig.pixel_format = fmt\n> +\n> +    if args.size:\n> +        w, h = [int(v) for v in args.size.split('x')]\n> +        streamconfig.size = libcam.Size(w, h)\n> +\n> +    ret = cam.configure(camconfig)\n> +    assert ret == 0\n> +\n> +    stream = streamconfig.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 {streamconfig} 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())","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 847BCBD160\n\tfor <parsemail@patchwork.libcamera.org>;\n\tThu, 26 May 2022 16:15:57 +0000 (UTC)","from lancelot.ideasonboard.com (localhost [IPv6:::1])\n\tby lancelot.ideasonboard.com (Postfix) with ESMTP id 39618611C1;\n\tThu, 26 May 2022 18:15:57 +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 8C04A60DB0\n\tfor <libcamera-devel@lists.libcamera.org>;\n\tThu, 26 May 2022 18:15:55 +0200 (CEST)","from pendragon.ideasonboard.com (unknown [37.120.212.14])\n\tby perceval.ideasonboard.com (Postfix) with ESMTPSA id 10A7B32A;\n\tThu, 26 May 2022 18:15:54 +0200 (CEST)"],"DKIM-Signature":["v=1; a=rsa-sha256; c=relaxed/simple; d=libcamera.org;\n\ts=mail; t=1653581757;\n\tbh=JeTlGut5VlQ191NLBxARAuh/+fopci6e9yOPZIOMTzw=;\n\th=Date:To:References:In-Reply-To:Subject:List-Id:List-Unsubscribe:\n\tList-Archive:List-Post:List-Help:List-Subscribe:From:Reply-To:Cc:\n\tFrom;\n\tb=I7BllJ74oNHGPEYkXmbSrswT9vuNi9HA7KlGqLQejGp1MUhQfUeivAPjtq9qNNtPo\n\thf8ixRl6wvEYNZCqqgyOFgOVAyPcDZwbH0D72jWgp3F4delrJs2qQWYXwGWmq2KPfP\n\tC6FYrqlJJM8889VWQzFkmR5d1yxDweN79nsdyTp2oJtvAdN1vrncd/m2SG7bshD/Om\n\tlsnRk92ng2JoWIgiM8RN08gEX2Av2dxFUl40D1o0T60VGts1BqKW6NVz9aum+QkdHh\n\t8e7J8fukUKxPhMc915rrqaogsxAg2bdBDdMyPZspuoAKTXCeyr3vK0KKPoaKkI/U4T\n\tT1fHQEhm7L7BQ==","v=1; a=rsa-sha256; c=relaxed/simple; d=ideasonboard.com;\n\ts=mail; t=1653581755;\n\tbh=JeTlGut5VlQ191NLBxARAuh/+fopci6e9yOPZIOMTzw=;\n\th=Date:From:To:Cc:Subject:References:In-Reply-To:From;\n\tb=RKmzL5kCCdQoN8K2KM0raZ7VrnsZycdzqNj1HmVaQiGspzQmIW+PaON9G0PLmX1KM\n\tURHFrD29tPIjH9SFxFLVsIKtk95bCkAaa1PZ7AsL8i+WpAQJNAyn8/ymEZZolEMPxk\n\tLsW9rom/CC3N3s/W7tq+BgzLXcZaJPKKDy1vjG2w="],"Authentication-Results":"lancelot.ideasonboard.com; dkim=pass (1024-bit key; \n\tunprotected) header.d=ideasonboard.com\n\theader.i=@ideasonboard.com\n\theader.b=\"RKmzL5kC\"; dkim-atps=neutral","Date":"Thu, 26 May 2022 19:15:49 +0300","To":"Tomi Valkeinen <tomi.valkeinen@ideasonboard.com>","Message-ID":"<Yo+ntcrv4vTae9NK@pendragon.ideasonboard.com>","References":"<20220524114610.41848-1-tomi.valkeinen@ideasonboard.com>\n\t<20220524114610.41848-13-tomi.valkeinen@ideasonboard.com>","MIME-Version":"1.0","Content-Type":"text/plain; charset=utf-8","Content-Disposition":"inline","In-Reply-To":"<20220524114610.41848-13-tomi.valkeinen@ideasonboard.com>","Subject":"Re: [libcamera-devel] [PATCH v2 12/19] 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":"Laurent Pinchart via libcamera-devel\n\t<libcamera-devel@lists.libcamera.org>","Reply-To":"Laurent Pinchart <laurent.pinchart@ideasonboard.com>","Cc":"libcamera-devel@lists.libcamera.org","Errors-To":"libcamera-devel-bounces@lists.libcamera.org","Sender":"\"libcamera-devel\" <libcamera-devel-bounces@lists.libcamera.org>"}}]