From patchwork Sat Sep 7 14:28:26 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Cheng-Hao Yang X-Patchwork-Id: 21193 Return-Path: X-Original-To: parsemail@patchwork.libcamera.org Delivered-To: parsemail@patchwork.libcamera.org Received: from lancelot.ideasonboard.com (lancelot.ideasonboard.com [92.243.16.209]) by patchwork.libcamera.org (Postfix) with ESMTPS id E5216C324C for ; Sat, 7 Sep 2024 14:31:24 +0000 (UTC) Received: from lancelot.ideasonboard.com (localhost [IPv6:::1]) by lancelot.ideasonboard.com (Postfix) with ESMTP id A5750634FC; Sat, 7 Sep 2024 16:31:21 +0200 (CEST) Authentication-Results: lancelot.ideasonboard.com; dkim=pass (1024-bit key; unprotected) header.d=chromium.org header.i=@chromium.org header.b="W3J/zO67"; dkim-atps=neutral Received: from mail-pf1-x432.google.com (mail-pf1-x432.google.com [IPv6:2607:f8b0:4864:20::432]) by lancelot.ideasonboard.com (Postfix) with ESMTPS id D0CD6633CC for ; Sat, 7 Sep 2024 16:31:19 +0200 (CEST) Received: by mail-pf1-x432.google.com with SMTP id d2e1a72fcca58-717911ef035so2308952b3a.3 for ; Sat, 07 Sep 2024 07:31:19 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=chromium.org; s=google; t=1725719478; x=1726324278; darn=lists.libcamera.org; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:cc:to:from:from:to:cc:subject:date :message-id:reply-to; bh=ykxXuMf7wvHOxfLwxRKz/cbPcfwSaWd3G7r3fOBmhAA=; b=W3J/zO67tqrCQoAEYhPy5HpcQz0B4ixaExqVfE5Hy1GJXPxFQ64tPBqUYo3B1QmRHH loF3IAPaEOvs3F9yh93gJQcfNkZQtd1R5oi8WioWtbQZARiv+qoXYeI06rCVTxgxjttA nUFabilcuB+YHKg6ernbSRAXdJ55oEwSzsF2M= X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1725719478; x=1726324278; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:cc:to:from:x-gm-message-state:from:to:cc :subject:date:message-id:reply-to; bh=ykxXuMf7wvHOxfLwxRKz/cbPcfwSaWd3G7r3fOBmhAA=; b=UrlV3BSUazrMztNhS/HH4LYn+cpbZQCM97OJ1tRZdM6Q4uSoIriJpQHNdyVgaCBsAt f2BYzSNQFdphNssqxR7XBE2jcrfOWlxaDNVxtqEYce0Y9CIpxIXXk7g1AgG/FreYAXwe 0YUBMmsRhCxdJHPArI561SFh6MOopqk+5uu7njEovBoCKf2g4ZIN7k8MzmgkPzzWPzGD S0tUQFFlomGYumu4Az4xprAt7O8MGDrG14Zyss9afQllmwOVYzmNnT69rl0I4RKwu1j9 7PgeqHriB5QraoFrou5jZWf6TvSiK/vJEPy0ba+MXd0aOnUzcVUcPh2PvA9beIlYK2Oz c5Gw== X-Gm-Message-State: AOJu0YzBIboVGfG0MooWgI7aUMG/lCl0oRC8eo4rsPiNrec54JlqGxJ7 GxGtDHC0JIhM57BI5e2Fn16usooWHvNnPOysuv27+iIe89skTJbY+WtefZUXs6Ki8N+oMMjKmQ4 = X-Google-Smtp-Source: AGHT+IE5tiwhrTyqS7fO21GJvUh3PV83d3SDENceuMWT3pehASWDmyAU6VSpSoz6sBHVP5UJ3Z2oPQ== X-Received: by 2002:a05:6a20:e687:b0:1cf:126c:49fb with SMTP id adf61e73a8af0-1cf1d20c5c7mr5996722637.43.1725719477713; Sat, 07 Sep 2024 07:31:17 -0700 (PDT) Received: from chenghaoyang-low.c.googlers.com.com (0.223.81.34.bc.googleusercontent.com. [34.81.223.0]) by smtp.gmail.com with ESMTPSA id d9443c01a7336-20710e33974sm9208935ad.104.2024.09.07.07.31.16 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Sat, 07 Sep 2024 07:31:17 -0700 (PDT) From: Harvey Yang X-Google-Original-From: Harvey Yang To: libcamera-devel@lists.libcamera.org Cc: Harvey Yang , Harvey Yang Subject: [PATCH v11 1/7] libcamera: add DmaBufAllocator::exportBuffers() Date: Sat, 7 Sep 2024 14:28:26 +0000 Message-ID: <20240907143110.2210711-2-chenghaoyang@google.com> X-Mailer: git-send-email 2.46.0.469.g59c65b2a67-goog In-Reply-To: <20240907143110.2210711-1-chenghaoyang@google.com> References: <20240907143110.2210711-1-chenghaoyang@google.com> MIME-Version: 1.0 X-BeenThere: libcamera-devel@lists.libcamera.org X-Mailman-Version: 2.1.29 Precedence: list List-Id: List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Errors-To: libcamera-devel-bounces@lists.libcamera.org Sender: "libcamera-devel" Add a helper function exportBuffers in DmaBufAllocator to make it easier to use. It'll be used in Virtual Pipeline Handler and SoftwareIsp. Signed-off-by: Harvey Yang Reviewed-by: Kieran Bingham --- .../libcamera/internal/dma_buf_allocator.h | 13 +++++ src/libcamera/dma_buf_allocator.cpp | 55 +++++++++++++++++++ 2 files changed, 68 insertions(+) diff --git a/include/libcamera/internal/dma_buf_allocator.h b/include/libcamera/internal/dma_buf_allocator.h index d2a0a0d1..66d3b419 100644 --- a/include/libcamera/internal/dma_buf_allocator.h +++ b/include/libcamera/internal/dma_buf_allocator.h @@ -7,11 +7,17 @@ #pragma once +#include +#include +#include + #include #include namespace libcamera { +class FrameBuffer; + class DmaBufAllocator { public: @@ -28,7 +34,14 @@ public: bool isValid() const { return providerHandle_.isValid(); } UniqueFD alloc(const char *name, std::size_t size); + int exportBuffers(unsigned int count, + const std::vector &frameSize, + std::vector> *buffers); + private: + std::unique_ptr createBuffer( + std::string name, const std::vector &frameSizes); + UniqueFD allocFromHeap(const char *name, std::size_t size); UniqueFD allocFromUDmaBuf(const char *name, std::size_t size); UniqueFD providerHandle_; diff --git a/src/libcamera/dma_buf_allocator.cpp b/src/libcamera/dma_buf_allocator.cpp index be6efb89..d2ac175f 100644 --- a/src/libcamera/dma_buf_allocator.cpp +++ b/src/libcamera/dma_buf_allocator.cpp @@ -23,6 +23,10 @@ #include #include +#include + +#include "libcamera/internal/formats.h" + /** * \file dma_buf_allocator.cpp * \brief dma-buf allocator @@ -205,4 +209,55 @@ UniqueFD DmaBufAllocator::alloc(const char *name, std::size_t size) return allocFromHeap(name, size); } +/** + * \brief Allocate and export buffers from the DmaBufAllocator + * \param[in] count The number of requested FrameBuffers + * \param[in] frameSizes The sizes of planes in each FrameBuffer + * \param[out] buffers Array of buffers successfully allocated + * + * \return The number of allocated buffers on success or a negative error code + * otherwise + */ +int DmaBufAllocator::exportBuffers(unsigned int count, + const std::vector &frameSizes, + std::vector> *buffers) +{ + for (unsigned int i = 0; i < count; ++i) { + std::unique_ptr buffer = + createBuffer("frame-" + std::to_string(i), frameSizes); + if (!buffer) { + LOG(DmaBufAllocator, Error) << "Unable to create buffer"; + + buffers->clear(); + return -EINVAL; + } + + buffers->push_back(std::move(buffer)); + } + + return count; +} + +std::unique_ptr +DmaBufAllocator::createBuffer(std::string name, + const std::vector &frameSizes) +{ + std::vector planes; + + unsigned int bufferSize = 0, offset = 0; + for (auto frameSize : frameSizes) + bufferSize += frameSize; + + SharedFD fd(alloc(name.c_str(), bufferSize)); + if (!fd.isValid()) + return nullptr; + + for (auto frameSize : frameSizes) { + planes.emplace_back(FrameBuffer::Plane{ fd, offset, frameSize }); + offset += frameSize; + } + + return std::make_unique(planes); +} + } /* namespace libcamera */ From patchwork Sat Sep 7 14:28:27 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Cheng-Hao Yang X-Patchwork-Id: 21194 Return-Path: X-Original-To: parsemail@patchwork.libcamera.org Delivered-To: parsemail@patchwork.libcamera.org Received: from lancelot.ideasonboard.com (lancelot.ideasonboard.com [92.243.16.209]) by patchwork.libcamera.org (Postfix) with ESMTPS id 102F3C324C for ; Sat, 7 Sep 2024 14:31:27 +0000 (UTC) Received: from lancelot.ideasonboard.com (localhost [IPv6:::1]) by lancelot.ideasonboard.com (Postfix) with ESMTP id 179C563500; Sat, 7 Sep 2024 16:31:25 +0200 (CEST) Authentication-Results: lancelot.ideasonboard.com; dkim=pass (1024-bit key; unprotected) header.d=chromium.org header.i=@chromium.org header.b="BY2826Vm"; dkim-atps=neutral Received: from mail-pl1-x62d.google.com (mail-pl1-x62d.google.com [IPv6:2607:f8b0:4864:20::62d]) by lancelot.ideasonboard.com (Postfix) with ESMTPS id 0B58F634F8 for ; Sat, 7 Sep 2024 16:31:21 +0200 (CEST) Received: by mail-pl1-x62d.google.com with SMTP id d9443c01a7336-206aee4073cso29906045ad.1 for ; Sat, 07 Sep 2024 07:31:20 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=chromium.org; s=google; t=1725719479; x=1726324279; darn=lists.libcamera.org; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:cc:to:from:from:to:cc:subject:date :message-id:reply-to; bh=TSaImx5SqvHvHcxkD0MKMd1PCjbqNKbkJmxxCDje1YU=; b=BY2826VmRUlbra7N3EeIDmc0ItegsO5PLHmnfNoReBXybON+CyW6ZHepKmRzZqo9s+ 6JEubRADw0w+1PFhHoZ1iMkN5lBH4W3DQbn7jK5Hk+trqR43kHx7XCqPvBADUQs6iKYB rwWQTSjXYfrKk/ke1y6Zksvf2v/QqOfRSttKg= X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1725719479; x=1726324279; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:cc:to:from:x-gm-message-state:from:to:cc :subject:date:message-id:reply-to; bh=TSaImx5SqvHvHcxkD0MKMd1PCjbqNKbkJmxxCDje1YU=; b=cc1EBtRtPCNJpZVO8qKNbsuQLB2j+Jii+z2KGpTBKxWR6GnqU8Wr0W5l3IGD7ddk6/ mys4TLRFysToF8WUWH0nw9qnIoW5PEIBK2/YcEKD60SdG/CBgHrf9MH7QRMnIXXFCjLN MGQlvMgIdLmd2+b07gpp2h4AFixyGcAXExm9wHDxPhk3YBtMsKYoc3p6oDUom3DxCGiW N3yjySPSvRRE7UFCHKJiYUQSg2Y2UntlT6P2/ByRKUln/RCNLlRtaigpzelaVj2IJKEu 0N+2j8sPNj4OUCqeRrIswvVKfdviXyNACAyCmv+Rlf0Uy5OjYKcIYmWwg3UwtviwOwln SGTQ== X-Gm-Message-State: AOJu0YwFWb+7emeY0a8GJUDrDgUIas6m4jAxqKaL/lczikXd/cZCUbWy 1BglsQyXdjTbVJnyewCCPgFBrXrNZQEvV03K1nm45Remvk6qeRk/8xioiEtiqKJPYiW9oqxrXvk = X-Google-Smtp-Source: AGHT+IF3uenv51M0VgfyL75oqyePqqnwaZpZhmw4KETWNkMf8046r30qnUu2O/4mv2DcHLb1cnnAlg== X-Received: by 2002:a17:903:2303:b0:206:c12d:abad with SMTP id d9443c01a7336-206f05523e9mr98570765ad.34.1725719479233; Sat, 07 Sep 2024 07:31:19 -0700 (PDT) Received: from chenghaoyang-low.c.googlers.com.com (0.223.81.34.bc.googleusercontent.com. [34.81.223.0]) by smtp.gmail.com with ESMTPSA id d9443c01a7336-20710e33974sm9208935ad.104.2024.09.07.07.31.17 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Sat, 07 Sep 2024 07:31:18 -0700 (PDT) From: Harvey Yang X-Google-Original-From: Harvey Yang To: libcamera-devel@lists.libcamera.org Cc: Harvey Yang , Harvey Yang , Laurent Pinchart Subject: [PATCH v11 2/7] libcamera: Remove PipelineHandler Fatal check of non-empty MediaDevices Date: Sat, 7 Sep 2024 14:28:27 +0000 Message-ID: <20240907143110.2210711-3-chenghaoyang@google.com> X-Mailer: git-send-email 2.46.0.469.g59c65b2a67-goog In-Reply-To: <20240907143110.2210711-1-chenghaoyang@google.com> References: <20240907143110.2210711-1-chenghaoyang@google.com> MIME-Version: 1.0 X-BeenThere: libcamera-devel@lists.libcamera.org X-Mailman-Version: 2.1.29 Precedence: list List-Id: List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Errors-To: libcamera-devel-bounces@lists.libcamera.org Sender: "libcamera-devel" The Fatal check of having at least one MediaDevice was to prevent pipeline handler implementations searching and owning media devices with custom conventions, instead of using the base function |acquireMediaDevice|. It also has the assumption that there's at least one media device to make a camera work. Now that the assumption will be broken by the virtual pipeline handler added in the following patches, and developers should be aware of the available functions in the base class to handle media devices, the Fatal check is no longer needed. Signed-off-by: Harvey Yang Reviewed-by: Laurent Pinchart --- src/libcamera/pipeline_handler.cpp | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/src/libcamera/pipeline_handler.cpp b/src/libcamera/pipeline_handler.cpp index e5940469..89a513e4 100644 --- a/src/libcamera/pipeline_handler.cpp +++ b/src/libcamera/pipeline_handler.cpp @@ -637,9 +637,14 @@ void PipelineHandler::registerCamera(std::shared_ptr camera) { cameras_.push_back(camera); - if (mediaDevices_.empty()) - LOG(Pipeline, Fatal) - << "Registering camera with no media devices!"; + if (mediaDevices_.empty()) { + /* + * For virtual devices with no MediaDevice, there are no system + * devices to register. + */ + manager_->_d()->addCamera(std::move(camera)); + return; + } /* * Walk the entity list and map the devnums of all capture video nodes From patchwork Sat Sep 7 14:28:28 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Cheng-Hao Yang X-Patchwork-Id: 21195 Return-Path: X-Original-To: parsemail@patchwork.libcamera.org Delivered-To: parsemail@patchwork.libcamera.org Received: from lancelot.ideasonboard.com (lancelot.ideasonboard.com [92.243.16.209]) by patchwork.libcamera.org (Postfix) with ESMTPS id F20A8C324C for ; Sat, 7 Sep 2024 14:31:28 +0000 (UTC) Received: from lancelot.ideasonboard.com (localhost [IPv6:::1]) by lancelot.ideasonboard.com (Postfix) with ESMTP id 51D87634FF; Sat, 7 Sep 2024 16:31:28 +0200 (CEST) Authentication-Results: lancelot.ideasonboard.com; dkim=pass (1024-bit key; unprotected) header.d=chromium.org header.i=@chromium.org header.b="fbdLz+4H"; dkim-atps=neutral Received: from mail-pl1-x630.google.com (mail-pl1-x630.google.com [IPv6:2607:f8b0:4864:20::630]) by lancelot.ideasonboard.com (Postfix) with ESMTPS id AE130634FD for ; Sat, 7 Sep 2024 16:31:22 +0200 (CEST) Received: by mail-pl1-x630.google.com with SMTP id d9443c01a7336-2068a7c9286so27535055ad.1 for ; Sat, 07 Sep 2024 07:31:22 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=chromium.org; s=google; t=1725719481; x=1726324281; darn=lists.libcamera.org; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:cc:to:from:from:to:cc:subject:date :message-id:reply-to; bh=lMPoRoLj1qLOTjmGEn/jJW8kdjjUwuimv2LrojCsP2s=; b=fbdLz+4HgXYkCx30EF1fuXldLDAArCp8CHrV1XDeow1VhMS4h+danQoG6/1cLPFZmN szgtzevxTG0qjgC8yBve2vhcApa0U7QL0jnq6fYiHTW7oVX+sYh+U/rZ+wxZXRynHhEa 8ehqlOYNo2vEgkzwxWZSijxISSnuMe0xKLpXk= X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1725719481; x=1726324281; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:cc:to:from:x-gm-message-state:from:to:cc :subject:date:message-id:reply-to; bh=lMPoRoLj1qLOTjmGEn/jJW8kdjjUwuimv2LrojCsP2s=; b=iQMuVEMVLybKLW5ggN+PRplw9vNkawHzWXeiA3Pk0wGGZTNIO8JOIHwW/tA64xwpl+ Ck7cxP0cBBqaKd3ajP996sfixzwQb2Ay5OQ1C777aVgHF46sT2SDL/VhmgDVZNyui2aG tsMFjAVftbEBokNCOIPooE8GZ+yZamLr6bnMGif5lwcsuTS6WIItYkun7n1Zn9Vul0QV 0UhsNjbNjMys/FXH7AHo2YBBLGj0zYywAQjJ/lQrDF/lLLG2rR3SsFsCcqhSkvFhEFYI JZHAST8X2Q+hZYcjWUrfcYccVCm1UvJJP+HeAiGUHi68kSMzzbsPrg1XoPry0go6h66J Dy1g== X-Gm-Message-State: AOJu0Yx8KunMZ3uTSaM2YgNCnxcVgHnNKhrCTEdS27O2/bQ70Ces7i9e MRIc9H1kXYBWBroc2QvBpaq8Y++J+GIzXcBf7gMlDs6RhGYAj2p60pGNQA21aM3HqaHPTXbLz5x W3w== X-Google-Smtp-Source: AGHT+IH3ecOadF5JSGoi8RZFgw8ACVd6VBZ/PTgbd4mBSPMDVq5WzG+OWQEogua+n2M7gTdQFF20Lw== X-Received: by 2002:a17:902:db0d:b0:205:4885:235e with SMTP id d9443c01a7336-206f05b1527mr63904035ad.39.1725719480684; Sat, 07 Sep 2024 07:31:20 -0700 (PDT) Received: from chenghaoyang-low.c.googlers.com.com (0.223.81.34.bc.googleusercontent.com. [34.81.223.0]) by smtp.gmail.com with ESMTPSA id d9443c01a7336-20710e33974sm9208935ad.104.2024.09.07.07.31.19 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Sat, 07 Sep 2024 07:31:20 -0700 (PDT) From: Harvey Yang X-Google-Original-From: Harvey Yang To: libcamera-devel@lists.libcamera.org Cc: Harvey Yang Subject: [PATCH v11 3/7] libcamera: virtual: Add VirtualPipelineHandler Date: Sat, 7 Sep 2024 14:28:28 +0000 Message-ID: <20240907143110.2210711-4-chenghaoyang@google.com> X-Mailer: git-send-email 2.46.0.469.g59c65b2a67-goog In-Reply-To: <20240907143110.2210711-1-chenghaoyang@google.com> References: <20240907143110.2210711-1-chenghaoyang@google.com> MIME-Version: 1.0 X-BeenThere: libcamera-devel@lists.libcamera.org X-Mailman-Version: 2.1.29 Precedence: list List-Id: List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Errors-To: libcamera-devel-bounces@lists.libcamera.org Sender: "libcamera-devel" From: Harvey Yang Add VirtualPipelineHandler for more unit tests and verfiy libcamera infrastructure works on devices without using hardware cameras. Signed-off-by: Harvey Yang Reviewed-by: Jacopo Mondi --- meson.build | 1 + meson_options.txt | 3 +- src/libcamera/pipeline/virtual/meson.build | 5 + src/libcamera/pipeline/virtual/virtual.cpp | 267 +++++++++++++++++++++ src/libcamera/pipeline/virtual/virtual.h | 89 +++++++ 5 files changed, 364 insertions(+), 1 deletion(-) create mode 100644 src/libcamera/pipeline/virtual/meson.build create mode 100644 src/libcamera/pipeline/virtual/virtual.cpp create mode 100644 src/libcamera/pipeline/virtual/virtual.h diff --git a/meson.build b/meson.build index 432ae133..ff9a70cf 100644 --- a/meson.build +++ b/meson.build @@ -214,6 +214,7 @@ pipelines_support = { 'simple': ['any'], 'uvcvideo': ['any'], 'vimc': ['test'], + 'virtual': ['test'], } if pipelines.contains('all') diff --git a/meson_options.txt b/meson_options.txt index 7aa41249..c91cd241 100644 --- a/meson_options.txt +++ b/meson_options.txt @@ -53,7 +53,8 @@ option('pipelines', 'rpi/vc4', 'simple', 'uvcvideo', - 'vimc' + 'vimc', + 'virtual' ], description : 'Select which pipeline handlers to build. If this is set to "auto", all the pipelines applicable to the target architecture will be built. If this is set to "all", all the pipelines will be built. If both are selected then "all" will take precedence.') diff --git a/src/libcamera/pipeline/virtual/meson.build b/src/libcamera/pipeline/virtual/meson.build new file mode 100644 index 00000000..ada1b335 --- /dev/null +++ b/src/libcamera/pipeline/virtual/meson.build @@ -0,0 +1,5 @@ +# SPDX-License-Identifier: CC0-1.0 + +libcamera_internal_sources += files([ + 'virtual.cpp', +]) diff --git a/src/libcamera/pipeline/virtual/virtual.cpp b/src/libcamera/pipeline/virtual/virtual.cpp new file mode 100644 index 00000000..f85ec3dd --- /dev/null +++ b/src/libcamera/pipeline/virtual/virtual.cpp @@ -0,0 +1,267 @@ +/* SPDX-License-Identifier: LGPL-2.1-or-later */ +/* + * Copyright (C) 2024, Google Inc. + * + * virtual.cpp - Pipeline handler for virtual cameras + */ + +#include "virtual.h" + +#include +#include +#include +#include +#include +#include + +#include + +#include +#include +#include +#include + +#include "libcamera/internal/camera.h" +#include "libcamera/internal/formats.h" +#include "libcamera/internal/pipeline_handler.h" + +namespace libcamera { + +LOG_DEFINE_CATEGORY(Virtual) + +namespace { + +uint64_t currentTimestamp() +{ + struct timespec ts; + if (clock_gettime(CLOCK_MONOTONIC, &ts) < 0) { + LOG(Virtual, Error) << "Get clock time fails"; + return 0; + } + + return ts.tv_sec * 1'000'000'000LL + ts.tv_nsec; +} + +} /* namespace */ + +VirtualCameraData::VirtualCameraData(PipelineHandler *pipe, + std::vector supportedResolutions) + : Camera::Private(pipe), supportedResolutions_(std::move(supportedResolutions)) +{ + for (const auto &resolution : supportedResolutions_) { + if (minResolutionSize_.isNull() || minResolutionSize_ > resolution.size) + minResolutionSize_ = resolution.size; + + maxResolutionSize_ = std::max(maxResolutionSize_, resolution.size); + } + + /* \todo Support multiple streams and pass multi_stream_test */ + streamConfigs_.resize(kMaxStream); +} + +VirtualCameraConfiguration::VirtualCameraConfiguration(VirtualCameraData *data) + : CameraConfiguration(), data_(data) +{ +} + +CameraConfiguration::Status VirtualCameraConfiguration::validate() +{ + Status status = Valid; + + if (config_.empty()) { + LOG(Virtual, Error) << "Empty config"; + return Invalid; + } + + /* Only one stream is supported */ + if (config_.size() > VirtualCameraData::kMaxStream) { + config_.resize(VirtualCameraData::kMaxStream); + status = Adjusted; + } + + for (StreamConfiguration &cfg : config_) { + bool found = false; + for (const auto &resolution : data_->supportedResolutions_) { + if (resolution.size.width == cfg.size.width && + resolution.size.height == cfg.size.height) { + found = true; + break; + } + } + + if (!found) { + /* + * \todo It's a pipeline's decision to choose a + * resolution when the exact one is not supported. + * Defining the default logic in PipelineHandler to + * find the closest resolution would be nice. + */ + cfg.size = data_->maxResolutionSize_; + status = Adjusted; + } + + const PixelFormatInfo &info = PixelFormatInfo::info(cfg.pixelFormat); + cfg.stride = info.stride(cfg.size.width, 0, 1); + cfg.frameSize = info.frameSize(cfg.size, 1); + + cfg.bufferCount = VirtualCameraConfiguration::kBufferCount; + + if (cfg.pixelFormat != formats::NV12) { + cfg.pixelFormat = formats::NV12; + LOG(Virtual, Debug) + << "Stream configuration adjusted to " << cfg.toString(); + status = Adjusted; + } + } + + return status; +} + +PipelineHandlerVirtual::PipelineHandlerVirtual(CameraManager *manager) + : PipelineHandler(manager), + dmaBufAllocator_(DmaBufAllocator::DmaBufAllocatorFlag::CmaHeap | + DmaBufAllocator::DmaBufAllocatorFlag::SystemHeap | + DmaBufAllocator::DmaBufAllocatorFlag::UDmaBuf) +{ +} + +std::unique_ptr +PipelineHandlerVirtual::generateConfiguration(Camera *camera, + Span roles) +{ + VirtualCameraData *data = cameraData(camera); + auto config = + std::make_unique(data); + + if (roles.empty()) + return config; + + for (const StreamRole role : roles) { + std::map> streamFormats; + PixelFormat pixelFormat = formats::NV12; + streamFormats[pixelFormat] = { { data->minResolutionSize_, data->maxResolutionSize_ } }; + StreamFormats formats(streamFormats); + StreamConfiguration cfg(formats); + cfg.pixelFormat = pixelFormat; + cfg.size = data->maxResolutionSize_; + cfg.bufferCount = VirtualCameraConfiguration::kBufferCount; + + switch (role) { + case StreamRole::StillCapture: + case StreamRole::VideoRecording: + case StreamRole::Viewfinder: + break; + + case StreamRole::Raw: + default: + LOG(Virtual, Error) + << "Requested stream role not supported: " << role; + config.reset(); + return config; + } + + config->addConfiguration(cfg); + } + + if (config->validate() == CameraConfiguration::Invalid) + config.reset(); + + return config; +} + +int PipelineHandlerVirtual::configure(Camera *camera, + CameraConfiguration *config) +{ + VirtualCameraData *data = cameraData(camera); + for (size_t i = 0; i < config->size(); ++i) + config->at(i).setStream(&data->streamConfigs_[i].stream); + + return 0; +} + +int PipelineHandlerVirtual::exportFrameBuffers([[maybe_unused]] Camera *camera, + Stream *stream, + std::vector> *buffers) +{ + if (!dmaBufAllocator_.isValid()) + return -ENOBUFS; + + const StreamConfiguration &config = stream->configuration(); + + auto info = PixelFormatInfo::info(config.pixelFormat); + + std::vector planeSizes; + for (size_t i = 0; i < info.planes.size(); ++i) + planeSizes.push_back(info.planeSize(config.size, i)); + + return dmaBufAllocator_.exportBuffers(config.bufferCount, planeSizes, buffers); +} + +int PipelineHandlerVirtual::start([[maybe_unused]] Camera *camera, + [[maybe_unused]] const ControlList *controls) +{ + return 0; +} + +void PipelineHandlerVirtual::stopDevice([[maybe_unused]] Camera *camera) +{ +} + +int PipelineHandlerVirtual::queueRequestDevice([[maybe_unused]] Camera *camera, + Request *request) +{ + /* \todo Read from the virtual video if any. */ + for (auto it : request->buffers()) + completeBuffer(request, it.second); + + request->metadata().set(controls::SensorTimestamp, currentTimestamp()); + completeRequest(request); + + return 0; +} + +// static +bool PipelineHandlerVirtual::created_ = false; + +bool PipelineHandlerVirtual::match([[maybe_unused]] DeviceEnumerator *enumerator) +{ + if (created_) + return false; + + created_ = true; + + /* \todo Add virtual cameras according to a config file. */ + + std::vector supportedResolutions; + supportedResolutions.resize(2); + supportedResolutions[0] = { .size = Size(1920, 1080), .frameRates = { 30 } }; + supportedResolutions[1] = { .size = Size(1280, 720), .frameRates = { 30 } }; + + std::unique_ptr data = + std::make_unique(this, supportedResolutions); + + data->properties_.set(properties::Location, properties::CameraLocationFront); + data->properties_.set(properties::Model, "Virtual Video Device"); + data->properties_.set(properties::PixelArrayActiveAreas, { Rectangle(Size(1920, 1080)) }); + + /* \todo Set FrameDurationLimits based on config. */ + ControlInfoMap::Map controls; + int64_t min_frame_duration = 33333, max_frame_duration = 33333; + controls[&controls::FrameDurationLimits] = ControlInfo(min_frame_duration, max_frame_duration); + data->controlInfo_ = ControlInfoMap(std::move(controls), controls::controls); + + /* Create and register the camera. */ + std::set streams; + for (auto &streamConfig : data->streamConfigs_) + streams.insert(&streamConfig.stream); + + const std::string id = "Virtual0"; + std::shared_ptr camera = Camera::create(std::move(data), id, streams); + registerCamera(std::move(camera)); + + return true; +} + +REGISTER_PIPELINE_HANDLER(PipelineHandlerVirtual, "virtual") + +} /* namespace libcamera */ diff --git a/src/libcamera/pipeline/virtual/virtual.h b/src/libcamera/pipeline/virtual/virtual.h new file mode 100644 index 00000000..fb3dbcad --- /dev/null +++ b/src/libcamera/pipeline/virtual/virtual.h @@ -0,0 +1,89 @@ +/* SPDX-License-Identifier: LGPL-2.1-or-later */ +/* + * Copyright (C) 2024, Google Inc. + * + * virtual.h - Pipeline handler for virtual cameras + */ + +#pragma once + +#include +#include + +#include + +#include "libcamera/internal/camera.h" +#include "libcamera/internal/dma_buf_allocator.h" +#include "libcamera/internal/pipeline_handler.h" + +namespace libcamera { + +class VirtualCameraData : public Camera::Private +{ +public: + const static unsigned int kMaxStream = 1; + + struct Resolution { + Size size; + std::vector frameRates; + }; + struct StreamConfig { + Stream stream; + }; + + VirtualCameraData(PipelineHandler *pipe, + std::vector supportedResolutions); + + ~VirtualCameraData() = default; + + const std::vector supportedResolutions_; + Size maxResolutionSize_; + Size minResolutionSize_; + + std::vector streamConfigs_; +}; + +class VirtualCameraConfiguration : public CameraConfiguration +{ +public: + static constexpr unsigned int kBufferCount = 4; + + VirtualCameraConfiguration(VirtualCameraData *data); + + Status validate() override; + +private: + const VirtualCameraData *data_; +}; + +class PipelineHandlerVirtual : public PipelineHandler +{ +public: + PipelineHandlerVirtual(CameraManager *manager); + + std::unique_ptr generateConfiguration(Camera *camera, + Span roles) override; + int configure(Camera *camera, CameraConfiguration *config) override; + + int exportFrameBuffers(Camera *camera, Stream *stream, + std::vector> *buffers) override; + + int start(Camera *camera, const ControlList *controls) override; + void stopDevice(Camera *camera) override; + + int queueRequestDevice(Camera *camera, Request *request) override; + + bool match(DeviceEnumerator *enumerator) override; + +private: + static bool created_; + + VirtualCameraData *cameraData(Camera *camera) + { + return static_cast(camera->_d()); + } + + DmaBufAllocator dmaBufAllocator_; +}; + +} /* namespace libcamera */ From patchwork Sat Sep 7 14:28:29 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Cheng-Hao Yang X-Patchwork-Id: 21196 Return-Path: X-Original-To: parsemail@patchwork.libcamera.org Delivered-To: parsemail@patchwork.libcamera.org Received: from lancelot.ideasonboard.com (lancelot.ideasonboard.com [92.243.16.209]) by patchwork.libcamera.org (Postfix) with ESMTPS id 70E12C324C for ; Sat, 7 Sep 2024 14:31:33 +0000 (UTC) Received: from lancelot.ideasonboard.com (localhost [IPv6:::1]) by lancelot.ideasonboard.com (Postfix) with ESMTP id 1B59B63500; Sat, 7 Sep 2024 16:31:33 +0200 (CEST) Authentication-Results: lancelot.ideasonboard.com; dkim=pass (1024-bit key; unprotected) header.d=chromium.org header.i=@chromium.org header.b="VwRUkRzc"; dkim-atps=neutral Received: from mail-pl1-x62f.google.com (mail-pl1-x62f.google.com [IPv6:2607:f8b0:4864:20::62f]) by lancelot.ideasonboard.com (Postfix) with ESMTPS id 6B5A8634F4 for ; Sat, 7 Sep 2024 16:31:24 +0200 (CEST) Received: by mail-pl1-x62f.google.com with SMTP id d9443c01a7336-2054e22ce3fso27814185ad.2 for ; Sat, 07 Sep 2024 07:31:24 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=chromium.org; s=google; t=1725719482; x=1726324282; darn=lists.libcamera.org; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:cc:to:from:from:to:cc:subject:date :message-id:reply-to; bh=TPTolxD0dbXfb95Xlm2OYyFA+j4DzV1KmlyOUgwk5UA=; b=VwRUkRzcQbC/WU+1BwJ5/Uhu8ZZ7xyjfH1puqOVM14ZBHMZpdXfVyF+FkoYhe1g8at K0iAujpWRzopIkvsU3fGecRr3JIKqY0/lMtvls83xguBz/v7mWt9oNxVJZz5APiEi4hs 1ZlpP8lFA3BlyddI5nKVcjIOKRIg5TeNsupas= X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1725719482; x=1726324282; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:cc:to:from:x-gm-message-state:from:to:cc :subject:date:message-id:reply-to; bh=TPTolxD0dbXfb95Xlm2OYyFA+j4DzV1KmlyOUgwk5UA=; b=lVteOtqfPfA0nzNCGWeStLXJttwaOtnd4UxrOYC75lq80uSj+tGzC1DTswY3aF0Sot UAMj5Hfqqjg4qjdV5o5sdS/hAarAi92okEebGdCtyWRqudTV/ZrUee4nuFYBvGKcc8h9 CjI5+/ws1rSJdd/9714aL1Ej8Kd3ab7bma/GbxD3gtEzzCE1MkBoChpilXKpJ4cIp4k9 E3ujp9Ilg7DTbZIcnBPGpB89XUmyVE3/ECZ5ATIEUMq1dHzfX77n8H6rKMQTmCFs5PuC yDXnZMnctBgINj+JNJWofyaovCyRI2/xBegN7xmal5IZLK2Tllg5BxbFa3+0kePXZ88n 8bYQ== X-Gm-Message-State: AOJu0YwzhA7z2jiMMjdmCh3yYoJXfac5U6wLStvcPgbXg3HNw4uwEmzU WZTC/N8TtsswYBv56uQ3hcDTQ/DDzZ/l1zqXyzDkqIuG3qNFd9yTtIHWR7VKM2rciDuGhK+UBi8 Bzw== X-Google-Smtp-Source: AGHT+IFvY4URNakxdhEgiNhWx21n5Mlvg8+rbxwLy1NbMgmmGVZCeUkCBuex4TtUyh+yU448IIC9EA== X-Received: by 2002:a17:902:e88a:b0:206:8f21:284e with SMTP id d9443c01a7336-206f05f68b0mr54423435ad.42.1725719482464; Sat, 07 Sep 2024 07:31:22 -0700 (PDT) Received: from chenghaoyang-low.c.googlers.com.com (0.223.81.34.bc.googleusercontent.com. [34.81.223.0]) by smtp.gmail.com with ESMTPSA id d9443c01a7336-20710e33974sm9208935ad.104.2024.09.07.07.31.20 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Sat, 07 Sep 2024 07:31:22 -0700 (PDT) From: Harvey Yang X-Google-Original-From: Harvey Yang To: libcamera-devel@lists.libcamera.org Cc: Konami Shu , Harvey Yang , Yunke Cao , Tomasz Figa Subject: [PATCH v11 4/7] libcamera: pipeline: Add test pattern for VirtualPipelineHandler Date: Sat, 7 Sep 2024 14:28:29 +0000 Message-ID: <20240907143110.2210711-5-chenghaoyang@google.com> X-Mailer: git-send-email 2.46.0.469.g59c65b2a67-goog In-Reply-To: <20240907143110.2210711-1-chenghaoyang@google.com> References: <20240907143110.2210711-1-chenghaoyang@google.com> MIME-Version: 1.0 X-BeenThere: libcamera-devel@lists.libcamera.org X-Mailman-Version: 2.1.29 Precedence: list List-Id: List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Errors-To: libcamera-devel-bounces@lists.libcamera.org Sender: "libcamera-devel" From: Konami Shu Add a test pattern generator class hierarchy for the Virtual pipeline handler. Implement two types of test patterns: color bars and diagonal lines generator and use them in the Virtual pipeline handler. Add a dependency for libyuv to the build system to generate images in NV12 format from the test pattern. Signed-off-by: Konami Shu Co-developed-by: Harvey Yang Co-developed-by: Yunke Cao Co-developed-by: Tomasz Figa libcamera: pipeline: Shift test pattern by 1 pixel left every frame - This write the buffer every frame - Shifting makes the frame rate dropped from about 160 to 40 Patchset1->2 - Use constant instead of using a magic number Patchset2->3 - Make shiftLeft() private Signed-off-by: Konami Shu Co-developed-by: Harvey Yang Co-developed-by: Yunke Cao Co-developed-by: Tomasz Figa Reviewed-by: Jacopo Mondi --- src/android/meson.build | 19 --- .../pipeline/virtual/frame_generator.h | 29 ++++ src/libcamera/pipeline/virtual/meson.build | 3 + .../virtual/test_pattern_generator.cpp | 140 ++++++++++++++++++ .../pipeline/virtual/test_pattern_generator.h | 57 +++++++ src/libcamera/pipeline/virtual/virtual.cpp | 38 ++++- src/libcamera/pipeline/virtual/virtual.h | 7 + src/meson.build | 19 +++ 8 files changed, 290 insertions(+), 22 deletions(-) create mode 100644 src/libcamera/pipeline/virtual/frame_generator.h create mode 100644 src/libcamera/pipeline/virtual/test_pattern_generator.cpp create mode 100644 src/libcamera/pipeline/virtual/test_pattern_generator.h diff --git a/src/android/meson.build b/src/android/meson.build index 68646120..6341ee8b 100644 --- a/src/android/meson.build +++ b/src/android/meson.build @@ -15,25 +15,6 @@ foreach dep : android_deps endif endforeach -libyuv_dep = dependency('libyuv', required : false) - -# Fallback to a subproject if libyuv isn't found, as it's typically not -# provided by distributions. -if not libyuv_dep.found() - cmake = import('cmake') - - libyuv_vars = cmake.subproject_options() - libyuv_vars.add_cmake_defines({'CMAKE_POSITION_INDEPENDENT_CODE': 'ON'}) - libyuv_vars.set_override_option('cpp_std', 'c++17') - libyuv_vars.append_compile_args('cpp', - '-Wno-sign-compare', - '-Wno-unused-variable', - '-Wno-unused-parameter') - libyuv_vars.append_link_args('-ljpeg') - libyuv = cmake.subproject('libyuv', options : libyuv_vars) - libyuv_dep = libyuv.dependency('yuv') -endif - android_deps += [libyuv_dep] android_hal_sources = files([ diff --git a/src/libcamera/pipeline/virtual/frame_generator.h b/src/libcamera/pipeline/virtual/frame_generator.h new file mode 100644 index 00000000..d8727b8f --- /dev/null +++ b/src/libcamera/pipeline/virtual/frame_generator.h @@ -0,0 +1,29 @@ +/* SPDX-License-Identifier: LGPL-2.1-or-later */ +/* + * Copyright (C) 2024, Google Inc. + * + * frame_generator.h - Virtual cameras helper to generate frames + */ + +#pragma once + +#include +#include + +namespace libcamera { + +class FrameGenerator +{ +public: + virtual ~FrameGenerator() = default; + + virtual void configure(const Size &size) = 0; + + virtual void generateFrame(const Size &size, + const FrameBuffer *buffer) = 0; + +protected: + FrameGenerator() {} +}; + +} /* namespace libcamera */ diff --git a/src/libcamera/pipeline/virtual/meson.build b/src/libcamera/pipeline/virtual/meson.build index ada1b335..0c537777 100644 --- a/src/libcamera/pipeline/virtual/meson.build +++ b/src/libcamera/pipeline/virtual/meson.build @@ -1,5 +1,8 @@ # SPDX-License-Identifier: CC0-1.0 libcamera_internal_sources += files([ + 'test_pattern_generator.cpp', 'virtual.cpp', ]) + +libcamera_deps += [libyuv_dep] diff --git a/src/libcamera/pipeline/virtual/test_pattern_generator.cpp b/src/libcamera/pipeline/virtual/test_pattern_generator.cpp new file mode 100644 index 00000000..7094818e --- /dev/null +++ b/src/libcamera/pipeline/virtual/test_pattern_generator.cpp @@ -0,0 +1,140 @@ +/* SPDX-License-Identifier: LGPL-2.1-or-later */ +/* + * Copyright (C) 2024, Google Inc. + * + * test_pattern_generator.cpp - Derived class of FrameGenerator for + * generating test patterns + */ + +#include "test_pattern_generator.h" + +#include + +#include "libcamera/internal/mapped_framebuffer.h" + +#include "libyuv/convert_from_argb.h" + +namespace libcamera { + +LOG_DECLARE_CATEGORY(Virtual) + +static const unsigned int kARGBSize = 4; + +void TestPatternGenerator::generateFrame(const Size &size, + const FrameBuffer *buffer) +{ + MappedFrameBuffer mappedFrameBuffer(buffer, + MappedFrameBuffer::MapFlag::Write); + + auto planes = mappedFrameBuffer.planes(); + + shiftLeft(size); + + /* Convert the template_ to the frame buffer */ + int ret = libyuv::ARGBToNV12( + template_.get(), size.width * kARGBSize, + planes[0].begin(), size.width, + planes[1].begin(), size.width, + size.width, size.height); + if (ret != 0) + LOG(Virtual, Error) << "ARGBToNV12() failed with " << ret; +} + +void TestPatternGenerator::shiftLeft(const Size &size) +{ + /* Store the first column temporarily */ + auto firstColumn = std::make_unique(size.height * kARGBSize); + for (size_t h = 0; h < size.height; h++) { + unsigned int index = h * size.width * kARGBSize; + unsigned int index1 = h * kARGBSize; + firstColumn[index1] = template_[index]; + firstColumn[index1 + 1] = template_[index + 1]; + firstColumn[index1 + 2] = template_[index + 2]; + firstColumn[index1 + 3] = 0x00; + } + + /* Overwrite template_ */ + uint8_t *buf = template_.get(); + for (size_t h = 0; h < size.height; h++) { + for (size_t w = 0; w < size.width - 1; w++) { + /* Overwrite with the pixel on the right */ + unsigned int index = (h * size.width + w + 1) * kARGBSize; + *buf++ = template_[index]; // B + *buf++ = template_[index + 1]; // G + *buf++ = template_[index + 2]; // R + *buf++ = 0x00; // A + } + /* Overwrite the new last column with the original first column */ + unsigned int index1 = h * kARGBSize; + *buf++ = firstColumn[index1]; // B + *buf++ = firstColumn[index1 + 1]; // G + *buf++ = firstColumn[index1 + 2]; // R + *buf++ = 0x00; // A + } +} + +ColorBarsGenerator::ColorBarsGenerator() = default; + +void ColorBarsGenerator::configure(const Size &size) +{ + constexpr uint8_t kColorBar[8][3] = { + // R, G, B + { 0xff, 0xff, 0xff }, // White + { 0xff, 0xff, 0x00 }, // Yellow + { 0x00, 0xff, 0xff }, // Cyan + { 0x00, 0xff, 0x00 }, // Green + { 0xff, 0x00, 0xff }, // Magenta + { 0xff, 0x00, 0x00 }, // Red + { 0x00, 0x00, 0xff }, // Blue + { 0x00, 0x00, 0x00 }, // Black + }; + + template_ = std::make_unique( + size.width * size.height * kARGBSize); + + unsigned int colorBarWidth = size.width / std::size(kColorBar); + + uint8_t *buf = template_.get(); + for (size_t h = 0; h < size.height; h++) { + for (size_t w = 0; w < size.width; w++) { + /* Repeat when the width is exceed */ + unsigned int index = (w / colorBarWidth) % std::size(kColorBar); + + *buf++ = kColorBar[index][2]; /* B */ + *buf++ = kColorBar[index][1]; /* G */ + *buf++ = kColorBar[index][0]; /* R */ + *buf++ = 0x00; /* A */ + } + } +} + +DiagonalLinesGenerator::DiagonalLinesGenerator() = default; + +void DiagonalLinesGenerator::configure(const Size &size) +{ + constexpr uint8_t kColorBar[8][3] = { + /* R, G, B */ + { 0xff, 0xff, 0xff }, /* White */ + { 0x00, 0x00, 0x00 }, /* Black */ + }; + + template_ = std::make_unique( + size.width * size.height * kARGBSize); + + unsigned int lineWidth = size.width / 10; + + uint8_t *buf = template_.get(); + for (size_t h = 0; h < size.height; h++) { + for (size_t w = 0; w < size.width; w++) { + /* Repeat when the width is exceed */ + int index = ((w + h) / lineWidth) % 2; + + *buf++ = kColorBar[index][2]; /* B */ + *buf++ = kColorBar[index][1]; /* G */ + *buf++ = kColorBar[index][0]; /* R */ + *buf++ = 0x00; /* A */ + } + } +} + +} /* namespace libcamera */ diff --git a/src/libcamera/pipeline/virtual/test_pattern_generator.h b/src/libcamera/pipeline/virtual/test_pattern_generator.h new file mode 100644 index 00000000..11bcb5f0 --- /dev/null +++ b/src/libcamera/pipeline/virtual/test_pattern_generator.h @@ -0,0 +1,57 @@ +/* SPDX-License-Identifier: LGPL-2.1-or-later */ +/* + * Copyright (C) 2024, Google Inc. + * + * test_pattern_generator.h - Derived class of FrameGenerator for + * generating test patterns + */ + +#pragma once + +#include + +#include +#include + +#include "frame_generator.h" + +namespace libcamera { + +enum class TestPattern : char { + ColorBars = 0, + DiagonalLines = 1, +}; + +class TestPatternGenerator : public FrameGenerator +{ +public: + void generateFrame(const Size &size, const FrameBuffer *buffer) override; + +protected: + /* Buffer of test pattern template */ + std::unique_ptr template_; + +private: + /* Shift the buffer by 1 pixel left each frame */ + void shiftLeft(const Size &size); +}; + +class ColorBarsGenerator : public TestPatternGenerator +{ +public: + ColorBarsGenerator(); + + /* Generate a template buffer of the color bar test pattern. */ + void configure(const Size &size) override; +}; + +class DiagonalLinesGenerator : public TestPatternGenerator +{ +public: + DiagonalLinesGenerator(); + + /* Generate a template buffer of the diagonal lines test pattern. */ + void configure(const Size &size) override; +}; + +} /* namespace libcamera */ diff --git a/src/libcamera/pipeline/virtual/virtual.cpp b/src/libcamera/pipeline/virtual/virtual.cpp index f85ec3dd..6e64aeee 100644 --- a/src/libcamera/pipeline/virtual/virtual.cpp +++ b/src/libcamera/pipeline/virtual/virtual.cpp @@ -173,8 +173,11 @@ int PipelineHandlerVirtual::configure(Camera *camera, CameraConfiguration *config) { VirtualCameraData *data = cameraData(camera); - for (size_t i = 0; i < config->size(); ++i) + for (size_t i = 0; i < config->size(); ++i) { config->at(i).setStream(&data->streamConfigs_[i].stream); + data->streamConfigs_[i].frameGenerator->configure( + data->streamConfigs_[i].stream.configuration().size); + } return 0; } @@ -210,9 +213,24 @@ void PipelineHandlerVirtual::stopDevice([[maybe_unused]] Camera *camera) int PipelineHandlerVirtual::queueRequestDevice([[maybe_unused]] Camera *camera, Request *request) { + VirtualCameraData *data = cameraData(camera); + /* \todo Read from the virtual video if any. */ - for (auto it : request->buffers()) - completeBuffer(request, it.second); + for (auto const &[stream, buffer] : request->buffers()) { + bool found = false; + /* map buffer and fill test patterns */ + for (auto &streamConfig : data->streamConfigs_) { + if (stream == &streamConfig.stream) { + found = true; + streamConfig.frameGenerator->generateFrame( + stream->configuration().size, buffer); + completeBuffer(request, buffer); + break; + } + } + if (!found) + LOG(Virtual, Fatal) << "Stream not defined"; + } request->metadata().set(controls::SensorTimestamp, currentTimestamp()); completeRequest(request); @@ -257,11 +275,25 @@ bool PipelineHandlerVirtual::match([[maybe_unused]] DeviceEnumerator *enumerator const std::string id = "Virtual0"; std::shared_ptr camera = Camera::create(std::move(data), id, streams); + + initFrameGenerator(camera.get()); + registerCamera(std::move(camera)); return true; } +void PipelineHandlerVirtual::initFrameGenerator(Camera *camera) +{ + auto data = cameraData(camera); + for (auto &streamConfig : data->streamConfigs_) { + if (data->testPattern_ == TestPattern::DiagonalLines) + streamConfig.frameGenerator = std::make_unique(); + else + streamConfig.frameGenerator = std::make_unique(); + } +} + REGISTER_PIPELINE_HANDLER(PipelineHandlerVirtual, "virtual") } /* namespace libcamera */ diff --git a/src/libcamera/pipeline/virtual/virtual.h b/src/libcamera/pipeline/virtual/virtual.h index fb3dbcad..09d73051 100644 --- a/src/libcamera/pipeline/virtual/virtual.h +++ b/src/libcamera/pipeline/virtual/virtual.h @@ -16,6 +16,8 @@ #include "libcamera/internal/dma_buf_allocator.h" #include "libcamera/internal/pipeline_handler.h" +#include "test_pattern_generator.h" + namespace libcamera { class VirtualCameraData : public Camera::Private @@ -29,6 +31,7 @@ public: }; struct StreamConfig { Stream stream; + std::unique_ptr frameGenerator; }; VirtualCameraData(PipelineHandler *pipe, @@ -36,6 +39,8 @@ public: ~VirtualCameraData() = default; + TestPattern testPattern_ = TestPattern::ColorBars; + const std::vector supportedResolutions_; Size maxResolutionSize_; Size minResolutionSize_; @@ -83,6 +88,8 @@ private: return static_cast(camera->_d()); } + void initFrameGenerator(Camera *camera); + DmaBufAllocator dmaBufAllocator_; }; diff --git a/src/meson.build b/src/meson.build index 165a77bb..91bea775 100644 --- a/src/meson.build +++ b/src/meson.build @@ -27,6 +27,25 @@ else ipa_sign_module = false endif +libyuv_dep = dependency('libyuv', required : false) + +# Fallback to a subproject if libyuv isn't found, as it's typically not +# provided by distributions. +if not libyuv_dep.found() + cmake = import('cmake') + + libyuv_vars = cmake.subproject_options() + libyuv_vars.add_cmake_defines({'CMAKE_POSITION_INDEPENDENT_CODE': 'ON'}) + libyuv_vars.set_override_option('cpp_std', 'c++17') + libyuv_vars.append_compile_args('cpp', + '-Wno-sign-compare', + '-Wno-unused-variable', + '-Wno-unused-parameter') + libyuv_vars.append_link_args('-ljpeg') + libyuv = cmake.subproject('libyuv', options : libyuv_vars) + libyuv_dep = libyuv.dependency('yuv') +endif + # libcamera must be built first as a dependency to the other components. subdir('libcamera') From patchwork Sat Sep 7 14:28:30 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Cheng-Hao Yang X-Patchwork-Id: 21197 Return-Path: X-Original-To: parsemail@patchwork.libcamera.org Delivered-To: parsemail@patchwork.libcamera.org Received: from lancelot.ideasonboard.com (lancelot.ideasonboard.com [92.243.16.209]) by patchwork.libcamera.org (Postfix) with ESMTPS id DBBD6C324C for ; Sat, 7 Sep 2024 14:31:35 +0000 (UTC) Received: from lancelot.ideasonboard.com (localhost [IPv6:::1]) by lancelot.ideasonboard.com (Postfix) with ESMTP id 79B77634FD; Sat, 7 Sep 2024 16:31:35 +0200 (CEST) Authentication-Results: lancelot.ideasonboard.com; dkim=pass (1024-bit key; unprotected) header.d=chromium.org header.i=@chromium.org header.b="PuuTb1K5"; dkim-atps=neutral Received: from mail-pg1-x535.google.com (mail-pg1-x535.google.com [IPv6:2607:f8b0:4864:20::535]) by lancelot.ideasonboard.com (Postfix) with ESMTPS id 99B7C634FB for ; Sat, 7 Sep 2024 16:31:26 +0200 (CEST) Received: by mail-pg1-x535.google.com with SMTP id 41be03b00d2f7-7d4ed6158bcso2279548a12.1 for ; Sat, 07 Sep 2024 07:31:26 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=chromium.org; s=google; t=1725719485; x=1726324285; darn=lists.libcamera.org; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:cc:to:from:from:to:cc:subject:date :message-id:reply-to; bh=Y9GNTrvwYKCoV2mHYZeY8RTk5KzZsF7cDP+kC+DuMZk=; b=PuuTb1K5QHDiqwQNTezlUlvDpSBR2XEOjZGAyf0cNS47QwpfA+AqZsF/RHjEjs05lR FOlsaHMh/8/Ab2+xJQNIp3wHbqt7v4htQk/grLTothrXRzpjAxP4zkNtl43rEGC2V5Hg 0TVjRjRREYOoPJyj7xr/RduBHIjAEKJm2Nmj0= X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1725719485; x=1726324285; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:cc:to:from:x-gm-message-state:from:to:cc :subject:date:message-id:reply-to; bh=Y9GNTrvwYKCoV2mHYZeY8RTk5KzZsF7cDP+kC+DuMZk=; b=ic/sOat76xVJzUNPX9ZrJkvJ9A49SjZdBiSDxE332h9JMsdsKCy6ZLNagYb0mh4zFp mpTsfllqfAkSUSsubC1DpftON1paGQoA2Gg8c4syXRbogMxZ97Fe86wmacAu/ZJVRLOS 8MQfNWH6U+FmyFZlkwKwXpLeh7Sg4Nh0vFwaUJsyPAFZbO22jNcFNbbHC6M8LeH3m4Ly 5Jp2rFQyS1i7F8cMpLLJVxiUbE40PXovYt8NMqPyGUmw8ST9HMDjiIniHthrCCfUsTvW i5GgoWFmYVOuyut6UoVXbC/VtfawyFfe/KAXjUERj2Pjf7HUbgO0eDSRJgwVvy5z1ukN pL3A== X-Gm-Message-State: AOJu0YxLLJ8krGtdT734r1yM/wGuis4AvSow4ZgI8d7bTEz/JlZYSUO+ h5wJ+7ay3p2uUpeoXuoQSlG81ulg2Y381T56Ztlxuz9K1uBXlsy2QgA2sL20HtLnXCy23+MasQg l2A== X-Google-Smtp-Source: AGHT+IGibm1ZPZY5nUEgx9hQ9R+Dh2j3CAW+fJporA9IrbAt53Pq4TilMpWCxu/RBQQyEqNA8MS4UQ== X-Received: by 2002:a17:902:d2d2:b0:206:b79e:5780 with SMTP id d9443c01a7336-206f0507dc6mr70177065ad.24.1725719484647; Sat, 07 Sep 2024 07:31:24 -0700 (PDT) Received: from chenghaoyang-low.c.googlers.com.com (0.223.81.34.bc.googleusercontent.com. [34.81.223.0]) by smtp.gmail.com with ESMTPSA id d9443c01a7336-20710e33974sm9208935ad.104.2024.09.07.07.31.22 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Sat, 07 Sep 2024 07:31:24 -0700 (PDT) From: Harvey Yang X-Google-Original-From: Harvey Yang To: libcamera-devel@lists.libcamera.org Cc: Konami Shu , Harvey Yang , Yunke Cao , Tomasz Figa Subject: [PATCH v11 5/7] libcamera: virtual: Read config and register cameras based on the config Date: Sat, 7 Sep 2024 14:28:30 +0000 Message-ID: <20240907143110.2210711-6-chenghaoyang@google.com> X-Mailer: git-send-email 2.46.0.469.g59c65b2a67-goog In-Reply-To: <20240907143110.2210711-1-chenghaoyang@google.com> References: <20240907143110.2210711-1-chenghaoyang@google.com> MIME-Version: 1.0 X-BeenThere: libcamera-devel@lists.libcamera.org X-Mailman-Version: 2.1.29 Precedence: list List-Id: List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Errors-To: libcamera-devel-bounces@lists.libcamera.org Sender: "libcamera-devel" From: Konami Shu This patch introduces the configuration file for Virtual Pipeline Handler. The config file is written in yaml, and the format is documented in `README.md`. The config file will define the camera with IDs, supported formats and image sources, etc. Only Test Patterns are supported now, while the next patches will add generators to read from real images. Signed-off-by: Konami Shu Co-developed-by: Harvey Yang Co-developed-by: Yunke Cao Co-developed-by: Tomasz Figa Reviewed-by: Jacopo Mondi --- src/libcamera/pipeline/virtual/README.md | 43 ++++ .../pipeline/virtual/data/virtual.yaml | 36 ++++ .../pipeline/virtual/frame_generator.h | 3 +- src/libcamera/pipeline/virtual/meson.build | 1 + src/libcamera/pipeline/virtual/parser.cpp | 197 ++++++++++++++++++ src/libcamera/pipeline/virtual/parser.h | 42 ++++ src/libcamera/pipeline/virtual/virtual.cpp | 56 ++--- src/libcamera/pipeline/virtual/virtual.h | 1 + 8 files changed, 350 insertions(+), 29 deletions(-) create mode 100644 src/libcamera/pipeline/virtual/README.md create mode 100644 src/libcamera/pipeline/virtual/data/virtual.yaml create mode 100644 src/libcamera/pipeline/virtual/parser.cpp create mode 100644 src/libcamera/pipeline/virtual/parser.h diff --git a/src/libcamera/pipeline/virtual/README.md b/src/libcamera/pipeline/virtual/README.md new file mode 100644 index 00000000..ef80bb48 --- /dev/null +++ b/src/libcamera/pipeline/virtual/README.md @@ -0,0 +1,43 @@ +# Virtual Pipeline Handler + +Virtual pipeline handler emulates fake external camera(s) on ChromeOS for testing. + +## Parse config file and register cameras + +- The config file is located at `src/libcamera/pipeline/virtual/data/virtual.yaml` + +### Config File Format +The config file contains the information about cameras' properties to register. +The config file should be a yaml file with dictionary of the cameraIds +associated with their properties as top level. The default value will be applied when any property is empty. + +Each camera block is a dictionary, containing the following keys: +- `supported_formats` (list of `VirtualCameraData::Resolution`, optional) : List of supported resolution and frame rates of the emulated camera + - `width` (`unsigned int`, default=1920): Width of the window resolution. This needs to be even. + - `height` (`unsigned int`, default=1080): Height of the window resolution. + - `frame_rates` (list of `int`, default=`[30,60]` ): Range of the frame rate (per second). If the list contains one value, it's the lower bound and the upper bound. If the list contains two values, the first is the lower bound and the second is the upper bound. No other number of values is allowed. +- `test_pattern` (`string`): Which test pattern to use as frames. The options are "bars", "lines". +- `location` (`string`, default="front"): The location of the camera. Support "front" and "back". This is displayed in qcam camera selection window but this does not change the output. +- `model` (`string`, default="Unknown"): The model name of the camera. This is displayed in qcam camera selection window but this does not change the output. + +Check `data/virtual.yaml` as the sample config file. + +### Implementation + +`Parser` class provides methods to parse the config file to register cameras +in Virtual Pipeline Handler. `parseConfigFile()` is exposed to use in +Virtual Pipeline Handler. + +This is the procedure of the Parser class: +1. `parseConfigFile()` parses the config file to `YamlObject` using `YamlParser::parse()`. + - Parse the top level of config file which are the camera ids and look into each camera properties. +2. For each camera, `parseCameraConfigData()` returns a camera with the configuration. + - The methods in the next step fill the data with the pointer to the Camera object. + - If the config file contains invalid configuration, this method returns nullptr. The camera will be skipped. +3. Parse each property and register the data. + - `parseSupportedFormats()`: Parses `supported_formats` in the config, which contains resolutions and frame rates. + - `parseTestPattern()`: Parses `test_pattern` in the config. + - `parseLocation()`: Parses `location` in the config. + - `parseModel()`: Parses `model` in the config. +4. Back to `parseConfigFile()` and append the camera configuration. +5. Returns a list of camera configurations. diff --git a/src/libcamera/pipeline/virtual/data/virtual.yaml b/src/libcamera/pipeline/virtual/data/virtual.yaml new file mode 100644 index 00000000..6b73ddf2 --- /dev/null +++ b/src/libcamera/pipeline/virtual/data/virtual.yaml @@ -0,0 +1,36 @@ +# SPDX-License-Identifier: CC0-1.0 +%YAML 1.1 +--- +"Virtual0": + supported_formats: + - width: 1920 + height: 1080 + frame_rates: + - 30 + - 60 + - width: 1680 + height: 1050 + frame_rates: + - 70 + - 80 + test_pattern: "lines" + location: "front" + model: "Virtual Video Device" +"Virtual1": + supported_formats: + - width: 800 + height: 600 + frame_rates: + - 60 + test_pattern: "bars" + location: "back" + model: "Virtual Video Device1" +"Virtual2": + supported_formats: + - width: 400 + height: 300 + test_pattern: "lines" + location: "front" + model: "Virtual Video Device2" +"Virtual3": + test_pattern: "bars" diff --git a/src/libcamera/pipeline/virtual/frame_generator.h b/src/libcamera/pipeline/virtual/frame_generator.h index d8727b8f..f68a795f 100644 --- a/src/libcamera/pipeline/virtual/frame_generator.h +++ b/src/libcamera/pipeline/virtual/frame_generator.h @@ -19,8 +19,7 @@ public: virtual void configure(const Size &size) = 0; - virtual void generateFrame(const Size &size, - const FrameBuffer *buffer) = 0; + virtual void generateFrame(const Size &size, const FrameBuffer *buffer) = 0; protected: FrameGenerator() {} diff --git a/src/libcamera/pipeline/virtual/meson.build b/src/libcamera/pipeline/virtual/meson.build index 0c537777..d72ac5be 100644 --- a/src/libcamera/pipeline/virtual/meson.build +++ b/src/libcamera/pipeline/virtual/meson.build @@ -1,6 +1,7 @@ # SPDX-License-Identifier: CC0-1.0 libcamera_internal_sources += files([ + 'parser.cpp', 'test_pattern_generator.cpp', 'virtual.cpp', ]) diff --git a/src/libcamera/pipeline/virtual/parser.cpp b/src/libcamera/pipeline/virtual/parser.cpp new file mode 100644 index 00000000..d861a52a --- /dev/null +++ b/src/libcamera/pipeline/virtual/parser.cpp @@ -0,0 +1,197 @@ +/* SPDX-License-Identifier: LGPL-2.1-or-later */ +/* + * Copyright (C) 2024, Google Inc. + * + * parser.cpp - Virtual cameras helper to parse config file + */ + +#include "parser.h" + +#include +#include + +#include + +#include +#include + +#include "libcamera/internal/pipeline_handler.h" +#include "libcamera/internal/yaml_parser.h" + +#include "virtual.h" + +namespace libcamera { + +LOG_DECLARE_CATEGORY(Virtual) + +std::vector> +Parser::parseConfigFile(File &file, PipelineHandler *pipe) +{ + std::vector> configurations; + + std::unique_ptr cameras = YamlParser::parse(file); + if (!cameras) { + LOG(Virtual, Error) << "Failed to pass config file."; + return configurations; + } + + if (!cameras->isDictionary()) { + LOG(Virtual, Error) << "Config file is not a dictionary at the top level."; + return configurations; + } + + /* Look into the configuration of each camera */ + for (const auto &[cameraId, cameraConfigData] : cameras->asDict()) { + std::unique_ptr data = + parseCameraConfigData(cameraConfigData, pipe); + /* Parse configData to data*/ + if (!data) { + /* Skip the camera if it has invalid config */ + LOG(Virtual, Error) << "Failed to parse config of the camera: " + << cameraId; + continue; + } + + data->id_ = cameraId; + ControlInfoMap::Map controls; + /* todo: Check which resolution's frame rate to be reported */ + controls[&controls::FrameDurationLimits] = + ControlInfo(int64_t(1000000 / data->supportedResolutions_[0].frameRates[1]), + int64_t(1000000 / data->supportedResolutions_[0].frameRates[0])); + data->controlInfo_ = ControlInfoMap(std::move(controls), controls::controls); + configurations.push_back(std::move(data)); + } + return configurations; +} + +std::unique_ptr +Parser::parseCameraConfigData(const YamlObject &cameraConfigData, + PipelineHandler *pipe) +{ + std::vector resolutions; + if (parseSupportedFormats(cameraConfigData, &resolutions)) + return nullptr; + + std::unique_ptr data = + std::make_unique(pipe, resolutions); + + if (parseTestPattern(cameraConfigData, data.get())) + return nullptr; + + if (parseLocation(cameraConfigData, data.get())) + return nullptr; + + if (parseModel(cameraConfigData, data.get())) + return nullptr; + + return data; +} + +int Parser::parseSupportedFormats(const YamlObject &cameraConfigData, + std::vector *resolutions) +{ + if (cameraConfigData.contains("supported_formats")) { + const YamlObject &supportedResolutions = cameraConfigData["supported_formats"]; + + for (const YamlObject &supportedResolution : supportedResolutions.asList()) { + unsigned int width = supportedResolution["width"].get(1920); + unsigned int height = supportedResolution["height"].get(1080); + if (width == 0 || height == 0) { + LOG(Virtual, Error) << "Invalid width or/and height"; + return -EINVAL; + } + if (width % 2 != 0) { + LOG(Virtual, Error) << "Invalid width: width needs to be even"; + return -EINVAL; + } + + std::vector frameRates; + if (supportedResolution.contains("frame_rates")) { + auto frameRatesList = + supportedResolution["frame_rates"].getList(); + if (!frameRatesList || (frameRatesList->size() != 1 && + frameRatesList->size() != 2)) { + LOG(Virtual, Error) << "Invalid frame_rates: either one or two values"; + return -EINVAL; + } + + if (frameRatesList->size() == 2 && + frameRatesList.value()[0] > frameRatesList.value()[1]) { + LOG(Virtual, Error) << "frame_rates's first value(lower bound)" + << " is higher than the second value(upper bound)"; + return -EINVAL; + } + frameRates.push_back(frameRatesList.value()[0]); + if (frameRatesList->size() == 2) + frameRates.push_back(frameRatesList.value()[1]); + else + frameRates.push_back(frameRatesList.value()[0]); + } else { + frameRates.push_back(30); + frameRates.push_back(60); + } + + resolutions->emplace_back( + VirtualCameraData::Resolution{ Size{ width, height }, + frameRates }); + } + } else { + resolutions->emplace_back( + VirtualCameraData::Resolution{ Size{ 1920, 1080 }, + { 30, 60 } }); + } + + return 0; +} + +int Parser::parseTestPattern(const YamlObject &cameraConfigData, VirtualCameraData *data) +{ + std::string testPattern = cameraConfigData["test_pattern"].get(""); + + /* Default value is "bars" */ + if (testPattern == "bars") { + data->testPattern_ = TestPattern::ColorBars; + } else if (testPattern == "lines") { + data->testPattern_ = TestPattern::DiagonalLines; + } else { + LOG(Virtual, Error) << "Test pattern: " << testPattern + << "is not supported"; + return -EINVAL; + } + return 0; +} + +int Parser::parseLocation(const YamlObject &cameraConfigData, VirtualCameraData *data) +{ + std::string location = cameraConfigData["location"].get(""); + + /* Default value is properties::CameraLocationFront */ + if (location == "front" || location == "") { + data->properties_.set(properties::Location, + properties::CameraLocationFront); + } else if (location == "back") { + data->properties_.set(properties::Location, + properties::CameraLocationBack); + } else { + LOG(Virtual, Error) << "location: " << location + << " is not supported"; + return -EINVAL; + } + + return 0; +} + +int Parser::parseModel(const YamlObject &cameraConfigData, VirtualCameraData *data) +{ + std::string model = cameraConfigData["model"].get(""); + + /* Default value is "Unknown" */ + if (model == "") + data->properties_.set(properties::Model, "Unknown"); + else + data->properties_.set(properties::Model, model); + + return 0; +} + +} /* namespace libcamera */ diff --git a/src/libcamera/pipeline/virtual/parser.h b/src/libcamera/pipeline/virtual/parser.h new file mode 100644 index 00000000..09c3c56b --- /dev/null +++ b/src/libcamera/pipeline/virtual/parser.h @@ -0,0 +1,42 @@ +/* SPDX-License-Identifier: LGPL-2.1-or-later */ +/* + * Copyright (C) 2024, Google Inc. + * + * parser.h - Virtual cameras helper to parse config file + */ + +#pragma once + +#include +#include + +#include + +#include "libcamera/internal/pipeline_handler.h" +#include "libcamera/internal/yaml_parser.h" + +#include "virtual.h" + +namespace libcamera { + +class Parser +{ +public: + Parser() {} + ~Parser() = default; + + std::vector> + parseConfigFile(File &file, PipelineHandler *pipe); + +private: + std::unique_ptr + parseCameraConfigData(const YamlObject &cameraConfigData, PipelineHandler *pipe); + + int parseSupportedFormats(const YamlObject &cameraConfigData, + std::vector *resolutions); + int parseTestPattern(const YamlObject &cameraConfigData, VirtualCameraData *data); + int parseLocation(const YamlObject &cameraConfigData, VirtualCameraData *data); + int parseModel(const YamlObject &cameraConfigData, VirtualCameraData *data); +}; + +} /* namespace libcamera */ diff --git a/src/libcamera/pipeline/virtual/virtual.cpp b/src/libcamera/pipeline/virtual/virtual.cpp index 6e64aeee..55bc30df 100644 --- a/src/libcamera/pipeline/virtual/virtual.cpp +++ b/src/libcamera/pipeline/virtual/virtual.cpp @@ -24,6 +24,9 @@ #include "libcamera/internal/camera.h" #include "libcamera/internal/formats.h" #include "libcamera/internal/pipeline_handler.h" +#include "libcamera/internal/yaml_parser.h" + +#include "parser.h" namespace libcamera { @@ -55,6 +58,9 @@ VirtualCameraData::VirtualCameraData(PipelineHandler *pipe, maxResolutionSize_ = std::max(maxResolutionSize_, resolution.size); } + properties_.set(properties::PixelArrayActiveAreas, + { Rectangle(maxResolutionSize_) }); + /* \todo Support multiple streams and pass multi_stream_test */ streamConfigs_.resize(kMaxStream); } @@ -248,37 +254,33 @@ bool PipelineHandlerVirtual::match([[maybe_unused]] DeviceEnumerator *enumerator created_ = true; - /* \todo Add virtual cameras according to a config file. */ - - std::vector supportedResolutions; - supportedResolutions.resize(2); - supportedResolutions[0] = { .size = Size(1920, 1080), .frameRates = { 30 } }; - supportedResolutions[1] = { .size = Size(1280, 720), .frameRates = { 30 } }; - - std::unique_ptr data = - std::make_unique(this, supportedResolutions); - - data->properties_.set(properties::Location, properties::CameraLocationFront); - data->properties_.set(properties::Model, "Virtual Video Device"); - data->properties_.set(properties::PixelArrayActiveAreas, { Rectangle(Size(1920, 1080)) }); - - /* \todo Set FrameDurationLimits based on config. */ - ControlInfoMap::Map controls; - int64_t min_frame_duration = 33333, max_frame_duration = 33333; - controls[&controls::FrameDurationLimits] = ControlInfo(min_frame_duration, max_frame_duration); - data->controlInfo_ = ControlInfoMap(std::move(controls), controls::controls); + File file(configurationFile("virtual", "virtual.yaml")); + bool isOpen = file.open(File::OpenModeFlag::ReadOnly); + if (!isOpen) { + LOG(Virtual, Error) << "Failed to open config file: " << file.fileName(); + return false; + } - /* Create and register the camera. */ - std::set streams; - for (auto &streamConfig : data->streamConfigs_) - streams.insert(&streamConfig.stream); + Parser parser; + auto configData = parser.parseConfigFile(file, this); + if (configData.size() == 0) { + LOG(Virtual, Error) << "Failed to parse any cameras from the config file: " + << file.fileName(); + return false; + } - const std::string id = "Virtual0"; - std::shared_ptr camera = Camera::create(std::move(data), id, streams); + /* Configure and register cameras with configData */ + for (auto &data : configData) { + std::set streams; + for (auto &streamConfig : data->streamConfigs_) + streams.insert(&streamConfig.stream); + std::string id = data->id_; + std::shared_ptr camera = Camera::create(std::move(data), id, streams); - initFrameGenerator(camera.get()); + initFrameGenerator(camera.get()); - registerCamera(std::move(camera)); + registerCamera(std::move(camera)); + } return true; } diff --git a/src/libcamera/pipeline/virtual/virtual.h b/src/libcamera/pipeline/virtual/virtual.h index 09d73051..8830e00f 100644 --- a/src/libcamera/pipeline/virtual/virtual.h +++ b/src/libcamera/pipeline/virtual/virtual.h @@ -39,6 +39,7 @@ public: ~VirtualCameraData() = default; + std::string id_; TestPattern testPattern_ = TestPattern::ColorBars; const std::vector supportedResolutions_; From patchwork Sat Sep 7 14:28:31 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Cheng-Hao Yang X-Patchwork-Id: 21198 Return-Path: X-Original-To: parsemail@patchwork.libcamera.org Delivered-To: parsemail@patchwork.libcamera.org Received: from lancelot.ideasonboard.com (lancelot.ideasonboard.com [92.243.16.209]) by patchwork.libcamera.org (Postfix) with ESMTPS id 65A83C3259 for ; Sat, 7 Sep 2024 14:31:37 +0000 (UTC) Received: from lancelot.ideasonboard.com (localhost [IPv6:::1]) by lancelot.ideasonboard.com (Postfix) with ESMTP id D7CFA634F4; Sat, 7 Sep 2024 16:31:36 +0200 (CEST) Authentication-Results: lancelot.ideasonboard.com; dkim=pass (1024-bit key; unprotected) header.d=chromium.org header.i=@chromium.org header.b="dOxadJ4/"; dkim-atps=neutral Received: from mail-pl1-x631.google.com (mail-pl1-x631.google.com [IPv6:2607:f8b0:4864:20::631]) by lancelot.ideasonboard.com (Postfix) with ESMTPS id AF79D63505 for ; Sat, 7 Sep 2024 16:31:28 +0200 (CEST) Received: by mail-pl1-x631.google.com with SMTP id d9443c01a7336-20688fbaeafso29019865ad.0 for ; Sat, 07 Sep 2024 07:31:28 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=chromium.org; s=google; t=1725719487; x=1726324287; darn=lists.libcamera.org; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:cc:to:from:from:to:cc:subject:date :message-id:reply-to; bh=K3Nj5TdQ66fojNPaNK9VCVEWEMA+f1mXeZ/KyGmrgnQ=; b=dOxadJ4/pncHsx96Lv25PZ08Yr42qfS/95UD1x+y77XdwObzVSDqXbSNIZ8bYVbdG/ ggO+DN6qhTAX1n1evWPB/Au5YmOhN/xlIIeXtQp0CX9gSYnpLMmH13ew8w+fIY7d6QWG av/Azzx+Bg2bm+aChkLpOMqbfoivRomYc2btU= X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1725719487; x=1726324287; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:cc:to:from:x-gm-message-state:from:to:cc :subject:date:message-id:reply-to; bh=K3Nj5TdQ66fojNPaNK9VCVEWEMA+f1mXeZ/KyGmrgnQ=; b=rXNt7XaNPgLzRhrxwRbVkLcsyFxe4RUJoPniC0c38wEn0wCb47r0yLoA/g+Ozxhlk2 RFF2vQlYSGKuLGsntNBkfuxyL8lCTAzSmgfXqto4A1NKDVakXugceGB2BBTv1H784RKG J5aIae/hmvXqyiMNamhZoc8VuPH2+o8jo2mmRcDkeJbbUvoXPZVQP0lrt79blR5SAnA9 sykRmPUkvqvpDlUGPyu/DM9OdlU1ULsyk6rkDuw2dRJS9dDsjlQ8BiOtk7XXGxIffatG e1+Yt4w1bqieiOiBKvwAJ5cGMsyWbbexWYcNoBVBBX8W8L1zJPDw0fF5AbDV3PlvQkA2 9vjw== X-Gm-Message-State: AOJu0YzsP0gt9ac1icr5kNUok7EoNh9kUdHjLtv008645sZjmtSxV37W V7x0FKO63KiMdVGgflCclSbsjzuZTgqdWNHuLtnbgj5c5/ZLWQDRGEmAFMzoa4HinMSlqd74zVf i1g== X-Google-Smtp-Source: AGHT+IHJgwUUReG3lrt4HGuK/DmeyPW296pAru+ql5a7ToR5xynjo+Lk9USp14qWK/U1MW5LufQG+A== X-Received: by 2002:a17:902:e886:b0:202:3432:230c with SMTP id d9443c01a7336-206f04e943fmr64132685ad.18.1725719486499; Sat, 07 Sep 2024 07:31:26 -0700 (PDT) Received: from chenghaoyang-low.c.googlers.com.com (0.223.81.34.bc.googleusercontent.com. [34.81.223.0]) by smtp.gmail.com with ESMTPSA id d9443c01a7336-20710e33974sm9208935ad.104.2024.09.07.07.31.24 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Sat, 07 Sep 2024 07:31:25 -0700 (PDT) From: Harvey Yang X-Google-Original-From: Harvey Yang To: libcamera-devel@lists.libcamera.org Cc: Konami Shu , Harvey Yang , Yunke Cao , Tomasz Figa Subject: [PATCH v11 6/7] libcamera: virtual: Add ImageFrameGenerator Date: Sat, 7 Sep 2024 14:28:31 +0000 Message-ID: <20240907143110.2210711-7-chenghaoyang@google.com> X-Mailer: git-send-email 2.46.0.469.g59c65b2a67-goog In-Reply-To: <20240907143110.2210711-1-chenghaoyang@google.com> References: <20240907143110.2210711-1-chenghaoyang@google.com> MIME-Version: 1.0 X-BeenThere: libcamera-devel@lists.libcamera.org X-Mailman-Version: 2.1.29 Precedence: list List-Id: List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Errors-To: libcamera-devel-bounces@lists.libcamera.org Sender: "libcamera-devel" From: Konami Shu Besides TestPatternGenerator, this patch adds ImageFrameGenerator that loads real images (jpg / jpeg for now) as the source and generates scaled frames. Signed-off-by: Konami Shu Co-developed-by: Harvey Yang Co-developed-by: Yunke Cao Co-developed-by: Tomasz Figa --- src/libcamera/pipeline/virtual/README.md | 9 +- .../virtual/image_frame_generator.cpp | 178 ++++++++++++++++++ .../pipeline/virtual/image_frame_generator.h | 54 ++++++ src/libcamera/pipeline/virtual/meson.build | 4 + src/libcamera/pipeline/virtual/parser.cpp | 76 +++++++- src/libcamera/pipeline/virtual/parser.h | 2 + src/libcamera/pipeline/virtual/utils.h | 17 ++ src/libcamera/pipeline/virtual/virtual.cpp | 60 ++++-- src/libcamera/pipeline/virtual/virtual.h | 24 ++- 9 files changed, 389 insertions(+), 35 deletions(-) create mode 100644 src/libcamera/pipeline/virtual/image_frame_generator.cpp create mode 100644 src/libcamera/pipeline/virtual/image_frame_generator.h create mode 100644 src/libcamera/pipeline/virtual/utils.h diff --git a/src/libcamera/pipeline/virtual/README.md b/src/libcamera/pipeline/virtual/README.md index ef80bb48..18c8341b 100644 --- a/src/libcamera/pipeline/virtual/README.md +++ b/src/libcamera/pipeline/virtual/README.md @@ -16,7 +16,13 @@ Each camera block is a dictionary, containing the following keys: - `width` (`unsigned int`, default=1920): Width of the window resolution. This needs to be even. - `height` (`unsigned int`, default=1080): Height of the window resolution. - `frame_rates` (list of `int`, default=`[30,60]` ): Range of the frame rate (per second). If the list contains one value, it's the lower bound and the upper bound. If the list contains two values, the first is the lower bound and the second is the upper bound. No other number of values is allowed. -- `test_pattern` (`string`): Which test pattern to use as frames. The options are "bars", "lines". +- `test_pattern` (`string`): Which test pattern to use as frames. The options are "bars", "lines". Cannot be set with `frames`. +- `frames` (dictionary): + - `path` (`string`): Path to an image, or path to a directory of a series of images. Cannot be set with `test_pattern`. + - The test patterns are "bars" which means color bars, and "lines" which means diagonal lines. + - The path to an image has ".jpg" extension. + - The path to a directory ends with "/". The name of the images in the directory are "{n}.jpg" with {n} is the sequence of images starting with 0. + - `scale_mode`(`string`, default="fill"): Scale mode when the frames are images. The only scale mode supported now is "fill". This does not affect the scale mode for now. - `location` (`string`, default="front"): The location of the camera. Support "front" and "back". This is displayed in qcam camera selection window but this does not change the output. - `model` (`string`, default="Unknown"): The model name of the camera. This is displayed in qcam camera selection window but this does not change the output. @@ -37,6 +43,7 @@ This is the procedure of the Parser class: 3. Parse each property and register the data. - `parseSupportedFormats()`: Parses `supported_formats` in the config, which contains resolutions and frame rates. - `parseTestPattern()`: Parses `test_pattern` in the config. + - `parseFrame()`: Parses `frames` in the config. - `parseLocation()`: Parses `location` in the config. - `parseModel()`: Parses `model` in the config. 4. Back to `parseConfigFile()` and append the camera configuration. diff --git a/src/libcamera/pipeline/virtual/image_frame_generator.cpp b/src/libcamera/pipeline/virtual/image_frame_generator.cpp new file mode 100644 index 00000000..db3efe15 --- /dev/null +++ b/src/libcamera/pipeline/virtual/image_frame_generator.cpp @@ -0,0 +1,178 @@ +/* SPDX-License-Identifier: LGPL-2.1-or-later */ +/* + * Copyright (C) 2024, Google Inc. + * + * image_frame_generator.cpp - Derived class of FrameGenerator for + * generating frames from images + */ + +#include "image_frame_generator.h" + +#include +#include +#include + +#include +#include + +#include + +#include "libcamera/internal/mapped_framebuffer.h" + +#include "libyuv/convert.h" +#include "libyuv/scale.h" + +namespace libcamera { + +LOG_DECLARE_CATEGORY(Virtual) + +/* + * Factory function to create an ImageFrameGenerator object. + * Read the images and convert them to buffers in NV12 format. + * Store the pointers to the buffers to a list (imageFrameDatas) + */ +std::unique_ptr +ImageFrameGenerator::create(ImageFrames &imageFrames) +{ + std::unique_ptr imageFrameGenerator = + std::make_unique(); + imageFrameGenerator->imageFrames_ = &imageFrames; + + /* + * For each file in the directory, load the image, + * convert it to NV12, and store the pointer. + */ + for (unsigned int i = 0; i < imageFrames.number.value_or(1); i++) { + std::filesystem::path path; + if (!imageFrames.number) + /* If the path is to an image */ + path = imageFrames.path; + else + /* If the path is to a directory */ + path = imageFrames.path / (std::to_string(i) + ".jpg"); + + File file(path); + if (!file.open(File::OpenModeFlag::ReadOnly)) { + LOG(Virtual, Error) << "Failed to open image file " << file.fileName() + << ": " << strerror(file.error()); + return nullptr; + } + + /* Read the image file to data */ + auto fileSize = file.size(); + auto buffer = std::make_unique(file.size()); + if (file.read({ buffer.get(), static_cast(fileSize) }) != fileSize) { + LOG(Virtual, Error) << "Failed to read file " << file.fileName() + << ": " << strerror(file.error()); + return nullptr; + } + + /* Get the width and height of the image */ + int width, height; + if (libyuv::MJPGSize(buffer.get(), fileSize, &width, &height)) { + LOG(Virtual, Error) << "Failed to get the size of the image file: " + << file.fileName(); + return nullptr; + } + + /* Convert to NV12 and write the data to tmpY and tmpUV */ + unsigned int halfWidth = (width + 1) / 2; + unsigned int halfHeight = (height + 1) / 2; + std::unique_ptr dstY = + std::make_unique(width * height); + std::unique_ptr dstUV = + std::make_unique(halfWidth * halfHeight * 2); + int ret = libyuv::MJPGToNV12(buffer.get(), fileSize, + dstY.get(), width, dstUV.get(), + width, width, height, width, height); + if (ret != 0) + LOG(Virtual, Error) << "MJPGToNV12() failed with " << ret; + + imageFrameGenerator->imageFrameDatas_.emplace_back( + ImageFrameData{ std::move(dstY), std::move(dstUV), + Size(width, height) }); + } + + return imageFrameGenerator; +} + +/* Scale the buffers for image frames. */ +void ImageFrameGenerator::configure(const Size &size) +{ + /* Reset the source images to prevent multiple configuration calls */ + scaledFrameDatas_.clear(); + frameCount_ = 0; + parameter_ = 0; + + for (unsigned int i = 0; i < imageFrames_->number.value_or(1); i++) { + /* Scale the imageFrameDatas_ to scaledY and scaledUV */ + unsigned int halfSizeWidth = (size.width + 1) / 2; + unsigned int halfSizeHeight = (size.height + 1) / 2; + std::unique_ptr scaledY = + std::make_unique(size.width * size.height); + std::unique_ptr scaledUV = + std::make_unique(halfSizeWidth * halfSizeHeight * 2); + auto &src = imageFrameDatas_[i]; + + /* + * \todo Some platforms might enforce stride due to GPU, like + * ChromeOS ciri (64). The weight needs to be a multiple of + * the stride to work properly for now. + */ + libyuv::NV12Scale(src.Y.get(), src.size.width, + src.UV.get(), src.size.width, + src.size.width, src.size.height, + scaledY.get(), size.width, scaledUV.get(), size.width, + size.width, size.height, libyuv::FilterMode::kFilterBilinear); + + scaledFrameDatas_.emplace_back( + ImageFrameData{ std::move(scaledY), std::move(scaledUV), size }); + } +} + +void ImageFrameGenerator::generateFrame(const Size &size, const FrameBuffer *buffer) +{ + /* Don't do anything when the list of buffers is empty*/ + ASSERT(!scaledFrameDatas_.empty()); + + MappedFrameBuffer mappedFrameBuffer(buffer, MappedFrameBuffer::MapFlag::Write); + + auto planes = mappedFrameBuffer.planes(); + + /* Make sure the frameCount does not over the number of images */ + frameCount_ %= imageFrames_->number.value_or(1); + + /* Write the scaledY and scaledUV to the mapped frame buffer */ + libyuv::NV12Copy(scaledFrameDatas_[frameCount_].Y.get(), size.width, + scaledFrameDatas_[frameCount_].UV.get(), size.width, planes[0].begin(), + size.width, planes[1].begin(), size.width, + size.width, size.height); + + /* proceed an image every 4 frames */ + /* \todo read the parameter_ from the configuration file? */ + parameter_++; + if (parameter_ % 4 == 0) + frameCount_++; +} + +/** + * \var ImageFrameGenerator::imageFrameDatas_ + * \brief List of pointers to the not scaled image buffers + */ + +/** + * \var ImageFrameGenerator::scaledFrameDatas_ + * \brief List of pointers to the scaled image buffers + */ + +/** + * \var ImageFrameGenerator::imageFrames_ + * \brief Pointer to the imageFrames_ in VirtualCameraData + */ + +/** + * \var ImageFrameGenerator::parameter_ + * \brief Speed parameter. Change to the next image every parameter_ frames + */ + +} /* namespace libcamera */ diff --git a/src/libcamera/pipeline/virtual/image_frame_generator.h b/src/libcamera/pipeline/virtual/image_frame_generator.h new file mode 100644 index 00000000..4ad8aad2 --- /dev/null +++ b/src/libcamera/pipeline/virtual/image_frame_generator.h @@ -0,0 +1,54 @@ +/* SPDX-License-Identifier: LGPL-2.1-or-later */ +/* + * Copyright (C) 2024, Google Inc. + * + * image_frame_generator.h - Derived class of FrameGenerator for + * generating frames from images + */ + +#pragma once + +#include +#include +#include +#include +#include + +#include "frame_generator.h" + +namespace libcamera { + +enum class ScaleMode : char { + Fill = 0, +}; + +/* Frame configuration provided by the config file */ +struct ImageFrames { + std::filesystem::path path; + ScaleMode scaleMode; + std::optional number; +}; + +class ImageFrameGenerator : public FrameGenerator +{ +public: + static std::unique_ptr create(ImageFrames &imageFrames); + +private: + struct ImageFrameData { + std::unique_ptr Y; + std::unique_ptr UV; + Size size; + }; + + void configure(const Size &size) override; + void generateFrame(const Size &size, const FrameBuffer *buffer) override; + + std::vector imageFrameDatas_; + std::vector scaledFrameDatas_; + ImageFrames *imageFrames_; + unsigned int frameCount_; + unsigned int parameter_; +}; + +} /* namespace libcamera */ diff --git a/src/libcamera/pipeline/virtual/meson.build b/src/libcamera/pipeline/virtual/meson.build index d72ac5be..395919b3 100644 --- a/src/libcamera/pipeline/virtual/meson.build +++ b/src/libcamera/pipeline/virtual/meson.build @@ -1,9 +1,13 @@ # SPDX-License-Identifier: CC0-1.0 libcamera_internal_sources += files([ + 'image_frame_generator.cpp', 'parser.cpp', 'test_pattern_generator.cpp', 'virtual.cpp', ]) +libjpeg = dependency('libjpeg', required : false) + libcamera_deps += [libyuv_dep] +libcamera_deps += [libjpeg] diff --git a/src/libcamera/pipeline/virtual/parser.cpp b/src/libcamera/pipeline/virtual/parser.cpp index d861a52a..5076e71c 100644 --- a/src/libcamera/pipeline/virtual/parser.cpp +++ b/src/libcamera/pipeline/virtual/parser.cpp @@ -52,12 +52,12 @@ Parser::parseConfigFile(File &file, PipelineHandler *pipe) continue; } - data->id_ = cameraId; + data->config_.id = cameraId; ControlInfoMap::Map controls; /* todo: Check which resolution's frame rate to be reported */ controls[&controls::FrameDurationLimits] = - ControlInfo(int64_t(1000000 / data->supportedResolutions_[0].frameRates[1]), - int64_t(1000000 / data->supportedResolutions_[0].frameRates[0])); + ControlInfo(int64_t(1000000 / data->config_.resolutions[0].frameRates[1]), + int64_t(1000000 / data->config_.resolutions[0].frameRates[0])); data->controlInfo_ = ControlInfoMap(std::move(controls), controls::controls); configurations.push_back(std::move(data)); } @@ -75,7 +75,8 @@ Parser::parseCameraConfigData(const YamlObject &cameraConfigData, std::unique_ptr data = std::make_unique(pipe, resolutions); - if (parseTestPattern(cameraConfigData, data.get())) + if (parseTestPattern(cameraConfigData, data.get()) && + parseFrame(cameraConfigData, data.get())) return nullptr; if (parseLocation(cameraConfigData, data.get())) @@ -148,16 +149,75 @@ int Parser::parseTestPattern(const YamlObject &cameraConfigData, VirtualCameraDa { std::string testPattern = cameraConfigData["test_pattern"].get(""); - /* Default value is "bars" */ if (testPattern == "bars") { - data->testPattern_ = TestPattern::ColorBars; + data->config_.frame = TestPattern::ColorBars; } else if (testPattern == "lines") { - data->testPattern_ = TestPattern::DiagonalLines; + data->config_.frame = TestPattern::DiagonalLines; } else { - LOG(Virtual, Error) << "Test pattern: " << testPattern + LOG(Virtual, Debug) << "Test pattern: " << testPattern << "is not supported"; return -EINVAL; } + + return 0; +} + +int Parser::parseFrame(const YamlObject &cameraConfigData, VirtualCameraData *data) +{ + const YamlObject &frames = cameraConfigData["frames"]; + + /* When there is no frames provided in the config file, use color bar test pattern */ + if (frames.size() == 0) { + data->config_.frame = TestPattern::ColorBars; + return 0; + } + + if (!frames.isDictionary()) { + LOG(Virtual, Error) << "'frames' is not a dictionary."; + return -EINVAL; + } + + std::string path = frames["path"].get(""); + + ScaleMode scaleMode; + if (auto ext = std::filesystem::path(path).extension(); + ext == ".jpg" || ext == ".jpeg") { + if (parseScaleMode(frames, &scaleMode)) + return -EINVAL; + data->config_.frame = ImageFrames{ path, scaleMode, std::nullopt }; + } else if (std::filesystem::is_directory(std::filesystem::symlink_status(path))) { + if (parseScaleMode(frames, &scaleMode)) + return -EINVAL; + + using std::filesystem::directory_iterator; + unsigned int numOfFiles = std::distance(directory_iterator(path), directory_iterator{}); + if (numOfFiles == 0) { + LOG(Virtual, Error) << "Empty directory"; + return -EINVAL; + } + data->config_.frame = ImageFrames{ path, scaleMode, numOfFiles }; + } else { + LOG(Virtual, Error) << "Frame: " << path << " is not supported"; + return -EINVAL; + } + + return 0; +} + +int Parser::parseScaleMode( + const YamlObject &framesConfigData, ScaleMode *scaleMode) +{ + std::string mode = framesConfigData["scale_mode"].get(""); + + /* Default value is fill */ + if (mode == "fill" || mode == "") { + *scaleMode = ScaleMode::Fill; + } else { + LOG(Virtual, Error) << "scaleMode: " << mode + << " is not supported"; + return -EINVAL; + } + return 0; } diff --git a/src/libcamera/pipeline/virtual/parser.h b/src/libcamera/pipeline/virtual/parser.h index 09c3c56b..f65616e3 100644 --- a/src/libcamera/pipeline/virtual/parser.h +++ b/src/libcamera/pipeline/virtual/parser.h @@ -35,8 +35,10 @@ private: int parseSupportedFormats(const YamlObject &cameraConfigData, std::vector *resolutions); int parseTestPattern(const YamlObject &cameraConfigData, VirtualCameraData *data); + int parseFrame(const YamlObject &cameraConfigData, VirtualCameraData *data); int parseLocation(const YamlObject &cameraConfigData, VirtualCameraData *data); int parseModel(const YamlObject &cameraConfigData, VirtualCameraData *data); + int parseScaleMode(const YamlObject &framesConfigData, ScaleMode *scaleMode); }; } /* namespace libcamera */ diff --git a/src/libcamera/pipeline/virtual/utils.h b/src/libcamera/pipeline/virtual/utils.h new file mode 100644 index 00000000..43a14d4b --- /dev/null +++ b/src/libcamera/pipeline/virtual/utils.h @@ -0,0 +1,17 @@ +/* SPDX-License-Identifier: LGPL-2.1-or-later */ +/* + * Copyright (C) 2024, Google Inc. + * + * utils.h - Utility types for Virtual Pipeline Handler + */ + +namespace libcamera { + +template +struct overloaded : Ts... { + using Ts::operator()...; +}; +template +overloaded(Ts...) -> overloaded; + +} /* namespace libcamera */ diff --git a/src/libcamera/pipeline/virtual/virtual.cpp b/src/libcamera/pipeline/virtual/virtual.cpp index 55bc30df..98aed412 100644 --- a/src/libcamera/pipeline/virtual/virtual.cpp +++ b/src/libcamera/pipeline/virtual/virtual.cpp @@ -27,6 +27,7 @@ #include "libcamera/internal/yaml_parser.h" #include "parser.h" +#include "utils.h" namespace libcamera { @@ -49,17 +50,18 @@ uint64_t currentTimestamp() VirtualCameraData::VirtualCameraData(PipelineHandler *pipe, std::vector supportedResolutions) - : Camera::Private(pipe), supportedResolutions_(std::move(supportedResolutions)) + : Camera::Private(pipe) { - for (const auto &resolution : supportedResolutions_) { - if (minResolutionSize_.isNull() || minResolutionSize_ > resolution.size) - minResolutionSize_ = resolution.size; + config_.resolutions = std::move(supportedResolutions); + for (const auto &resolution : config_.resolutions) { + if (config_.minResolutionSize.isNull() || config_.minResolutionSize > resolution.size) + config_.minResolutionSize = resolution.size; - maxResolutionSize_ = std::max(maxResolutionSize_, resolution.size); + config_.maxResolutionSize = std::max(config_.maxResolutionSize, resolution.size); } properties_.set(properties::PixelArrayActiveAreas, - { Rectangle(maxResolutionSize_) }); + { Rectangle(config_.maxResolutionSize) }); /* \todo Support multiple streams and pass multi_stream_test */ streamConfigs_.resize(kMaxStream); @@ -87,7 +89,7 @@ CameraConfiguration::Status VirtualCameraConfiguration::validate() for (StreamConfiguration &cfg : config_) { bool found = false; - for (const auto &resolution : data_->supportedResolutions_) { + for (const auto &resolution : data_->config_.resolutions) { if (resolution.size.width == cfg.size.width && resolution.size.height == cfg.size.height) { found = true; @@ -102,7 +104,7 @@ CameraConfiguration::Status VirtualCameraConfiguration::validate() * Defining the default logic in PipelineHandler to * find the closest resolution would be nice. */ - cfg.size = data_->maxResolutionSize_; + cfg.size = data_->config_.maxResolutionSize; status = Adjusted; } @@ -145,11 +147,11 @@ PipelineHandlerVirtual::generateConfiguration(Camera *camera, for (const StreamRole role : roles) { std::map> streamFormats; PixelFormat pixelFormat = formats::NV12; - streamFormats[pixelFormat] = { { data->minResolutionSize_, data->maxResolutionSize_ } }; + streamFormats[pixelFormat] = { { data->config_.minResolutionSize, data->config_.maxResolutionSize } }; StreamFormats formats(streamFormats); StreamConfiguration cfg(formats); cfg.pixelFormat = pixelFormat; - cfg.size = data->maxResolutionSize_; + cfg.size = data->config_.maxResolutionSize; cfg.bufferCount = VirtualCameraConfiguration::kBufferCount; switch (role) { @@ -181,6 +183,7 @@ int PipelineHandlerVirtual::configure(Camera *camera, VirtualCameraData *data = cameraData(camera); for (size_t i = 0; i < config->size(); ++i) { config->at(i).setStream(&data->streamConfigs_[i].stream); + /* Start reading the images/generating test patterns */ data->streamConfigs_[i].frameGenerator->configure( data->streamConfigs_[i].stream.configuration().size); } @@ -274,10 +277,14 @@ bool PipelineHandlerVirtual::match([[maybe_unused]] DeviceEnumerator *enumerator std::set streams; for (auto &streamConfig : data->streamConfigs_) streams.insert(&streamConfig.stream); - std::string id = data->id_; + std::string id = data->config_.id; std::shared_ptr camera = Camera::create(std::move(data), id, streams); - initFrameGenerator(camera.get()); + if (!initFrameGenerator(camera.get())) { + LOG(Virtual, Error) << "Failed to initialize frame " + << "generator for camera: " << id; + continue; + } registerCamera(std::move(camera)); } @@ -285,15 +292,30 @@ bool PipelineHandlerVirtual::match([[maybe_unused]] DeviceEnumerator *enumerator return true; } -void PipelineHandlerVirtual::initFrameGenerator(Camera *camera) +bool PipelineHandlerVirtual::initFrameGenerator(Camera *camera) { auto data = cameraData(camera); - for (auto &streamConfig : data->streamConfigs_) { - if (data->testPattern_ == TestPattern::DiagonalLines) - streamConfig.frameGenerator = std::make_unique(); - else - streamConfig.frameGenerator = std::make_unique(); - } + auto &frame = data->config_.frame; + std::visit(overloaded{ + [&](TestPattern &testPattern) { + for (auto &streamConfig : data->streamConfigs_) { + if (testPattern == TestPattern::DiagonalLines) + streamConfig.frameGenerator = std::make_unique(); + else + streamConfig.frameGenerator = std::make_unique(); + } + }, + [&](ImageFrames &imageFrames) { + for (auto &streamConfig : data->streamConfigs_) + streamConfig.frameGenerator = ImageFrameGenerator::create(imageFrames); + } }, + frame); + + for (auto &streamConfig : data->streamConfigs_) + if (!streamConfig.frameGenerator) + return false; + + return true; } REGISTER_PIPELINE_HANDLER(PipelineHandlerVirtual, "virtual") diff --git a/src/libcamera/pipeline/virtual/virtual.h b/src/libcamera/pipeline/virtual/virtual.h index 8830e00f..efa97e88 100644 --- a/src/libcamera/pipeline/virtual/virtual.h +++ b/src/libcamera/pipeline/virtual/virtual.h @@ -8,6 +8,8 @@ #pragma once #include +#include +#include #include #include @@ -16,10 +18,14 @@ #include "libcamera/internal/dma_buf_allocator.h" #include "libcamera/internal/pipeline_handler.h" +#include "frame_generator.h" +#include "image_frame_generator.h" #include "test_pattern_generator.h" namespace libcamera { +using VirtualFrame = std::variant; + class VirtualCameraData : public Camera::Private { public: @@ -33,18 +39,22 @@ public: Stream stream; std::unique_ptr frameGenerator; }; + /* The config file is parsed to the Configuration struct */ + struct Configuration { + std::string id; + std::vector resolutions; + VirtualFrame frame; + + Size maxResolutionSize; + Size minResolutionSize; + }; VirtualCameraData(PipelineHandler *pipe, std::vector supportedResolutions); ~VirtualCameraData() = default; - std::string id_; - TestPattern testPattern_ = TestPattern::ColorBars; - - const std::vector supportedResolutions_; - Size maxResolutionSize_; - Size minResolutionSize_; + Configuration config_; std::vector streamConfigs_; }; @@ -89,7 +99,7 @@ private: return static_cast(camera->_d()); } - void initFrameGenerator(Camera *camera); + bool initFrameGenerator(Camera *camera); DmaBufAllocator dmaBufAllocator_; }; From patchwork Sat Sep 7 14:28:32 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Cheng-Hao Yang X-Patchwork-Id: 21199 Return-Path: X-Original-To: parsemail@patchwork.libcamera.org Delivered-To: parsemail@patchwork.libcamera.org Received: from lancelot.ideasonboard.com (lancelot.ideasonboard.com [92.243.16.209]) by patchwork.libcamera.org (Postfix) with ESMTPS id 030DDC324C for ; Sat, 7 Sep 2024 14:31:38 +0000 (UTC) Received: from lancelot.ideasonboard.com (localhost [IPv6:::1]) by lancelot.ideasonboard.com (Postfix) with ESMTP id E096263504; Sat, 7 Sep 2024 16:31:37 +0200 (CEST) Authentication-Results: lancelot.ideasonboard.com; dkim=pass (1024-bit key; unprotected) header.d=chromium.org header.i=@chromium.org header.b="KNaC4HGa"; dkim-atps=neutral Received: from mail-pl1-x629.google.com (mail-pl1-x629.google.com [IPv6:2607:f8b0:4864:20::629]) by lancelot.ideasonboard.com (Postfix) with ESMTPS id 425F7634EE for ; Sat, 7 Sep 2024 16:31:30 +0200 (CEST) Received: by mail-pl1-x629.google.com with SMTP id d9443c01a7336-2055a3f80a4so22202305ad.2 for ; Sat, 07 Sep 2024 07:31:30 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=chromium.org; s=google; t=1725719488; x=1726324288; darn=lists.libcamera.org; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:cc:to:from:from:to:cc:subject:date :message-id:reply-to; bh=uFCyayGX03aYOPVPXaPrf192CZnV0LxtxK3RtRGtom8=; b=KNaC4HGawqqV5OlX1YjdoZo2gPaGUtiowq9XKWkaBkHkZVQZYM3vtc6qQJr6du3mEi c3+mVlnSzhIjxLtdh9lzc05T5wx77sGggmFkwmJ10OEDGERyme7I62R0KDbJhIwYBiG+ /0+dmr3i7U265OU17DEsp3vOct6m4nZVSmNhs= X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1725719488; x=1726324288; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:cc:to:from:x-gm-message-state:from:to:cc :subject:date:message-id:reply-to; bh=uFCyayGX03aYOPVPXaPrf192CZnV0LxtxK3RtRGtom8=; b=NQ8MkYAgpm03Y/sPyxdF87xCfQDaAeVQo2N9FIrzPF9zObcI8ShEd0xzz1F3kZ/+wp 5acFF9bjqQJWnm+79t5wrbzKmmfiwHuABBhOFoE0U6yJfSS2pad4NFnm94OpblYihErk gY0JzdEZTmaS9yRYPYwHZXuO8RPxX1rRgkIKNZRyE/ndBcgU6esVGrUW34UQrGsDuPeJ On7of8iCGDt9v+6yKjfUM5dUEpNNesdW6cz6BPW5g5mDJZiI14sW1PsJXSAehGdwNesn OgZx1rrZx23z/YbBj27zXBqPVfXNt+0ex9R24JbGVfRrfElyEpPaj7gpP1dPEkYmiuHY 4RkQ== X-Gm-Message-State: AOJu0YyEIiSoDWcdzpyWQjF/Cb6u9a/i1GnlCvD49vkaLNvwqyiLSufu /TDdYr57Z1dyKkuoOzGqcV7PByXr1x76cqQiHojlR4d4wR84e78RGjZ+qas2EHLxVE9o7umHNOi 9xQ== X-Google-Smtp-Source: AGHT+IFnSJDdKSGFKgr0Z/nK4wzh6QgHgVNo8Z+Bez3TwS226gXxSaUXwVexzgUOmlpPZK0PXYeifA== X-Received: by 2002:a17:902:e885:b0:206:d69d:9ca6 with SMTP id d9443c01a7336-206f04e1af6mr80070055ad.10.1725719488076; Sat, 07 Sep 2024 07:31:28 -0700 (PDT) Received: from chenghaoyang-low.c.googlers.com.com (0.223.81.34.bc.googleusercontent.com. [34.81.223.0]) by smtp.gmail.com with ESMTPSA id d9443c01a7336-20710e33974sm9208935ad.104.2024.09.07.07.31.26 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Sat, 07 Sep 2024 07:31:27 -0700 (PDT) From: Harvey Yang X-Google-Original-From: Harvey Yang To: libcamera-devel@lists.libcamera.org Cc: Harvey Yang , Harvey Yang , Milan Zamazal Subject: [PATCH v11 7/7] libcamera: software_isp: Refactor SoftwareIsp to use DmaBufAllocator::exportBuffers Date: Sat, 7 Sep 2024 14:28:32 +0000 Message-ID: <20240907143110.2210711-8-chenghaoyang@google.com> X-Mailer: git-send-email 2.46.0.469.g59c65b2a67-goog In-Reply-To: <20240907143110.2210711-1-chenghaoyang@google.com> References: <20240907143110.2210711-1-chenghaoyang@google.com> MIME-Version: 1.0 X-BeenThere: libcamera-devel@lists.libcamera.org X-Mailman-Version: 2.1.29 Precedence: list List-Id: List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Errors-To: libcamera-devel-bounces@lists.libcamera.org Sender: "libcamera-devel" As the helper function DmaBufAllocator::exportBuffers is added, we can avoid some code duplication in SoftwareIsp as well. Signed-off-by: Harvey Yang Reviewed-by: Milan Zamazal Reviewed-by: Kieran Bingham --- src/libcamera/software_isp/software_isp.cpp | 20 +------------------- 1 file changed, 1 insertion(+), 19 deletions(-) diff --git a/src/libcamera/software_isp/software_isp.cpp b/src/libcamera/software_isp/software_isp.cpp index 1140372c..3455f13a 100644 --- a/src/libcamera/software_isp/software_isp.cpp +++ b/src/libcamera/software_isp/software_isp.cpp @@ -255,25 +255,7 @@ int SoftwareIsp::exportBuffers(const Stream *stream, unsigned int count, if (stream == nullptr) return -EINVAL; - for (unsigned int i = 0; i < count; i++) { - const std::string name = "frame-" + std::to_string(i); - const size_t frameSize = debayer_->frameSize(); - - FrameBuffer::Plane outPlane; - outPlane.fd = SharedFD(dmaHeap_.alloc(name.c_str(), frameSize)); - if (!outPlane.fd.isValid()) { - LOG(SoftwareIsp, Error) - << "failed to allocate a dma_buf"; - return -ENOMEM; - } - outPlane.offset = 0; - outPlane.length = frameSize; - - std::vector planes{ outPlane }; - buffers->emplace_back(std::make_unique(std::move(planes))); - } - - return count; + return dmaHeap_.exportBuffers(count, { debayer_->frameSize() }, buffers); } /**