From patchwork Mon Sep 30 06:29:42 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Harvey Yang X-Patchwork-Id: 21415 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 B7D23C32D4 for ; Mon, 30 Sep 2024 06:33:58 +0000 (UTC) Received: from lancelot.ideasonboard.com (localhost [IPv6:::1]) by lancelot.ideasonboard.com (Postfix) with ESMTP id A318F63518; Mon, 30 Sep 2024 08:33:57 +0200 (CEST) Authentication-Results: lancelot.ideasonboard.com; dkim=pass (1024-bit key; unprotected) header.d=chromium.org header.i=@chromium.org header.b="G57J0jVc"; dkim-atps=neutral Received: from mail-pf1-x434.google.com (mail-pf1-x434.google.com [IPv6:2607:f8b0:4864:20::434]) by lancelot.ideasonboard.com (Postfix) with ESMTPS id 246B46350F for ; Mon, 30 Sep 2024 08:33:51 +0200 (CEST) Received: by mail-pf1-x434.google.com with SMTP id d2e1a72fcca58-71971d2099cso3268312b3a.2 for ; Sun, 29 Sep 2024 23:33:51 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=chromium.org; s=google; t=1727678029; x=1728282829; 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=KYSCW2eznOAuCeDgQqEiD1QpvzOUGC3v4J7VHyWiUIo=; b=G57J0jVcJvBbmetJ62YzWj+tJA3sklKQAyKmy/j/KFUDQ69A/0cqPpSTl8Z0Sxj6o8 IxXOGC2Dc2rAfWWYmR7LhjOnSVUYwTU4zvSpta6RyjP6ZfXcaEmcduabQc+m0QKfydJG v+ICQxNh5hjFMxbwvOaJq4tE7aVNpvQa5bymE= X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1727678029; x=1728282829; 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=KYSCW2eznOAuCeDgQqEiD1QpvzOUGC3v4J7VHyWiUIo=; b=CSbGZ4ix3RdXY3loxOdwD0yhZin5Vr0sJpE6BlwJizZp1ozII02DO0fta5OUNLBtb/ /JaVdiv/UBA9OpF7WiPunomY34MvY1eTtlaCJK2mexjYHiLli7NkBy51EWXoPaBQAEIE Q4oi6x3P5WIEVee/G06/S1xqZwfkBd+ku61j3SrFF9dsw1Yx16ZalEy0C1OkpB/FuRCS pzVFLCaGAERxQXQfyMozqcdxhqHoBgmjDNGskyeXg4UD7NoVUXFUKBDBHrSEV4lYSrIm VMw6T+DMjrxJNbAmJEp8Qq2HA+88RBFS0vAQw/lrXT4uQuiYiXPfxbMIW0DWkQVSsAMk DBRw== X-Gm-Message-State: AOJu0YxPRfVou+7rd5dTAtPBFiPHUI0nII4EpuD5Mzo65UYWsX38HJP7 5XOMOpzZPIw1lVuEcWX1Q4TG/HZNeaVBCZYkXBPC8lxlRmrr9j+k8VmJKYcsCAE3RQ9Q8wOuEuI = X-Google-Smtp-Source: AGHT+IHTM1CmX5ehzEM3kxh5RF41j7+zN9LyNjVIo54n3wAf6QiO4XLetsfQYZFw/WJyUBwveuBwVw== X-Received: by 2002:a05:6a00:4fd2:b0:717:87d6:fdd2 with SMTP id d2e1a72fcca58-71b25f00ff4mr19143193b3a.4.1727678029187; Sun, 29 Sep 2024 23:33:49 -0700 (PDT) Received: from chenghaoyang-low.c.googlers.com.com (208.158.221.35.bc.googleusercontent.com. [35.221.158.208]) by smtp.gmail.com with ESMTPSA id d2e1a72fcca58-71b265166e2sm5487671b3a.131.2024.09.29.23.33.47 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Sun, 29 Sep 2024 23:33:48 -0700 (PDT) From: Harvey Yang X-Google-Original-From: Harvey Yang To: libcamera-devel@lists.libcamera.org Cc: Harvey Yang , Harvey Yang , Kieran Bingham , Jacopo Mondi Subject: [PATCH v14 1/7] libcamera: add DmaBufAllocator::exportBuffers() Date: Mon, 30 Sep 2024 06:29:42 +0000 Message-ID: <20240930063342.3014837-2-chenghaoyang@google.com> X-Mailer: git-send-email 2.46.1.824.gd892dcdcdd-goog In-Reply-To: <20240930063342.3014837-1-chenghaoyang@google.com> References: <20240930063342.3014837-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 Reviewed-by: Jacopo Mondi --- .../libcamera/internal/dma_buf_allocator.h | 13 +++++ src/libcamera/dma_buf_allocator.cpp | 57 +++++++++++++++++++ 2 files changed, 70 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..f8ed3de2 100644 --- a/src/libcamera/dma_buf_allocator.cpp +++ b/src/libcamera/dma_buf_allocator.cpp @@ -22,6 +22,9 @@ #include #include +#include + +#include /** * \file dma_buf_allocator.cpp @@ -205,4 +208,58 @@ 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 + * + * Planes in a FrameBuffer are allocated with a single dma buf. + * \todo Add the option to allocate each plane with a dma buf respectively. + * + * \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 Mon Sep 30 06:29:43 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Harvey Yang X-Patchwork-Id: 21416 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 E73D3C3257 for ; Mon, 30 Sep 2024 06:34:01 +0000 (UTC) Received: from lancelot.ideasonboard.com (localhost [IPv6:::1]) by lancelot.ideasonboard.com (Postfix) with ESMTP id 0FAF763518; Mon, 30 Sep 2024 08:34:01 +0200 (CEST) Authentication-Results: lancelot.ideasonboard.com; dkim=pass (1024-bit key; unprotected) header.d=chromium.org header.i=@chromium.org header.b="YuUQE9Sw"; dkim-atps=neutral Received: from mail-pg1-x52f.google.com (mail-pg1-x52f.google.com [IPv6:2607:f8b0:4864:20::52f]) by lancelot.ideasonboard.com (Postfix) with ESMTPS id BB01863512 for ; Mon, 30 Sep 2024 08:33:52 +0200 (CEST) Received: by mail-pg1-x52f.google.com with SMTP id 41be03b00d2f7-7db238d07b3so3393393a12.2 for ; Sun, 29 Sep 2024 23:33:52 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=chromium.org; s=google; t=1727678031; x=1728282831; 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=kiUmVXVsj2k0GDB+36LjnEpbTRYu3p9GSgHQdhpEEMY=; b=YuUQE9Sw9Mf6CY67ztmx7vV5eyCgH29e8iyepgaGM4cNlnX+EImbURFG9Keqf1t87o bqxHauKeRirOzPDDYmabaQW2/fY7bkJ6yxcAEb8g+6YU9uSApBU/a4dHr26UMWz5nanz R1POUIXHSIUGECx2+BJJjDD6pciN31xDw3qNk= X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1727678031; x=1728282831; 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=kiUmVXVsj2k0GDB+36LjnEpbTRYu3p9GSgHQdhpEEMY=; b=rkHW+xGhZQjDdztIKXGONVba8mjlkVcIxBkE5Opu52tJOq0THZvQtCjh8SFdsxfaAF Xr19VFqtazKBgAd3gU921Sh7XXdrBVsMq6oavU/Vlcw6FFjdjKJ76qMXVcgVSLdlkkIu Md/gzE9Hq0OS9TPfz7lWfw9elFJrAhnA63+4DCn9QTIQzg99yxqQxlEvlrxBtc2pGlXF HUJe8DglYCcKbWqL7TEQhlYQV2oxQe2k2+1BmmFDAKX0aMDymaikYMQ4JNNtFdstbg23 vd8H+GKhapJsJRaqdV3x40Qd9Jt6edj4qZr2FoVl1QYojH/rMeadREh3pnxBUpdZCq2g w2lw== X-Gm-Message-State: AOJu0Yz9bxBa20IEjbOmvFj00MEqeCbBaHaiacqdnN+VEUFsWcSJpQpB 1RNph678EUcx9X4CjBT48Z1ryrHeEp8MgK0CY98tmiQ3LjEzxCaAzVVn7U7q5a4e2h/KoPzXP1M = X-Google-Smtp-Source: AGHT+IFQ8kPHAz+7QdmuTluFHhcW/RLpJsPLaqiWLCyFraOok/vzNs/Y+JmbSyjPDtT0cFDT6rmYMg== X-Received: by 2002:a05:6a20:5194:b0:1d5:10c3:adcd with SMTP id adf61e73a8af0-1d510c3ae36mr5941154637.31.1727678030673; Sun, 29 Sep 2024 23:33:50 -0700 (PDT) Received: from chenghaoyang-low.c.googlers.com.com (208.158.221.35.bc.googleusercontent.com. [35.221.158.208]) by smtp.gmail.com with ESMTPSA id d2e1a72fcca58-71b265166e2sm5487671b3a.131.2024.09.29.23.33.49 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Sun, 29 Sep 2024 23:33:50 -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 v14 2/7] libcamera: Remove PipelineHandler Fatal check of non-empty MediaDevices Date: Mon, 30 Sep 2024 06:29:43 +0000 Message-ID: <20240930063342.3014837-3-chenghaoyang@google.com> X-Mailer: git-send-email 2.46.1.824.gd892dcdcdd-goog In-Reply-To: <20240930063342.3014837-1-chenghaoyang@google.com> References: <20240930063342.3014837-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 Reviewed-by: Kieran Bingham --- 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 Mon Sep 30 06:29:44 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Harvey Yang X-Patchwork-Id: 21417 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 4B81CC32D4 for ; Mon, 30 Sep 2024 06:34:06 +0000 (UTC) Received: from lancelot.ideasonboard.com (localhost [IPv6:::1]) by lancelot.ideasonboard.com (Postfix) with ESMTP id 668F963520; Mon, 30 Sep 2024 08:34:05 +0200 (CEST) Authentication-Results: lancelot.ideasonboard.com; dkim=pass (1024-bit key; unprotected) header.d=chromium.org header.i=@chromium.org header.b="jxcPa6uG"; dkim-atps=neutral Received: from mail-pg1-x530.google.com (mail-pg1-x530.google.com [IPv6:2607:f8b0:4864:20::530]) by lancelot.ideasonboard.com (Postfix) with ESMTPS id E199762C92 for ; Mon, 30 Sep 2024 08:33:54 +0200 (CEST) Received: by mail-pg1-x530.google.com with SMTP id 41be03b00d2f7-7d50e865b7aso3126475a12.0 for ; Sun, 29 Sep 2024 23:33:54 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=chromium.org; s=google; t=1727678032; x=1728282832; 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=wSXvEpeAq88KA7GGtwleKftwpSAO3e16Y5ff6zIFlLY=; b=jxcPa6uGoDyZ2HX8ktOoxH4Q1rIEvD/GaGM1aqwJS85vIbmlbdM6bTHoEzcvXiHjkc vbgLUQr9rQPcVqWgkym0dflarWhwnhiObmkDRR0pQLvKz8DjbCqQby6fqivOHqdj5Jmv CCX6hPdoZX2c+eJMb1gpzbpzqNlBbZVTyZzno= X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1727678032; x=1728282832; 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=wSXvEpeAq88KA7GGtwleKftwpSAO3e16Y5ff6zIFlLY=; b=joRRVlDp2KhX/EcH3CbIg6x+vZQsQy+ZLdzzSxlSFJ8L/rcYrp1zQI3Uy7jA0r/068 4y+Eh/FyvKu8FgKcIYhbQ7yDvh1jrjB1v1lMCOeXqA8XxWomHAzJIqfKbet9AyBHUjt9 mbk/vO+fUJdQh47psxTiCPIb0V2oemhl/GoEOtvgkAuEhnDuPY9rHHyGCB5gE6rPJgwh yD70F3iG61xlaXaRFpyQIofxM43QsAMmWNJuPOax0waJqHG62ddhoOxGZTDc/kkZW1Cu 7CN0xhBkQ86O1voLdfMxsCElK2VqBm47PU4igD7s3dsscgwp8Kk57EYrhpvyXvA/CcS1 0qOQ== X-Gm-Message-State: AOJu0YwymMTvlTG6WKnyHRb50PKUcluoEevJelp2ZlpQnrnTNVuN+85c FqYrG5/yAD68Nmps1QYjPzm1qkCGyDV4epl/XKUBi9OzN2TbXa7zk0ymKYMujXe17EHWiEMtZjE = X-Google-Smtp-Source: AGHT+IGS8za+Tb77t4DDXtnz/l9f5thwaXV4jCzx5hmkkighWjRzaHb9AMRaAkSJ1/n3ctTnUjc28w== X-Received: by 2002:a05:6a20:d43:b0:1cf:5578:9cba with SMTP id adf61e73a8af0-1d4fa68db67mr18052671637.11.1727678032395; Sun, 29 Sep 2024 23:33:52 -0700 (PDT) Received: from chenghaoyang-low.c.googlers.com.com (208.158.221.35.bc.googleusercontent.com. [35.221.158.208]) by smtp.gmail.com with ESMTPSA id d2e1a72fcca58-71b265166e2sm5487671b3a.131.2024.09.29.23.33.50 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Sun, 29 Sep 2024 23:33:51 -0700 (PDT) From: Harvey Yang X-Google-Original-From: Harvey Yang To: libcamera-devel@lists.libcamera.org Cc: Harvey Yang , Jacopo Mondi Subject: [PATCH v14 3/7] libcamera: virtual: Add VirtualPipelineHandler Date: Mon, 30 Sep 2024 06:29:44 +0000 Message-ID: <20240930063342.3014837-4-chenghaoyang@google.com> X-Mailer: git-send-email 2.46.1.824.gd892dcdcdd-goog In-Reply-To: <20240930063342.3014837-1-chenghaoyang@google.com> References: <20240930063342.3014837-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 Reviewed-by: Kieran Bingham --- meson.build | 1 + meson_options.txt | 3 +- src/libcamera/pipeline/virtual/meson.build | 5 + src/libcamera/pipeline/virtual/virtual.cpp | 317 +++++++++++++++++++++ src/libcamera/pipeline/virtual/virtual.h | 45 +++ 5 files changed, 370 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 63e45465..5e533b0c 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..d1584f59 --- /dev/null +++ b/src/libcamera/pipeline/virtual/virtual.cpp @@ -0,0 +1,317 @@ +/* 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 +#include + +#include +#include + +#include +#include +#include +#include +#include +#include + +#include "libcamera/internal/camera.h" +#include "libcamera/internal/dma_buf_allocator.h" +#include "libcamera/internal/formats.h" +#include "libcamera/internal/pipeline_handler.h" + +namespace libcamera { + +LOG_DEFINE_CATEGORY(Virtual) + +namespace { + +uint64_t currentTimestamp() +{ + const auto now = std::chrono::steady_clock::now(); + auto nsecs = std::chrono::duration_cast( + now.time_since_epoch()); + + return nsecs.count(); +} + +} /* namespace */ + +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_; +}; + +/* static */ +bool PipelineHandlerVirtual::created_ = false; + +VirtualCameraData::VirtualCameraData(PipelineHandler *pipe, + const std::vector &supportedResolutions) + : Camera::Private(pipe), supportedResolutions_(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; + } + + if (cfg.pixelFormat != formats::NV12) { + cfg.pixelFormat = formats::NV12; + LOG(Virtual, Debug) + << "Stream configuration adjusted to " << cfg.toString(); + 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; + } + + 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) { + 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; + } + + 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; + + config->addConfiguration(cfg); + } + + ASSERT(config->validate() != CameraConfiguration::Invalid); + + return config; +} + +int PipelineHandlerVirtual::configure(Camera *camera, + CameraConfiguration *config) +{ + VirtualCameraData *data = cameraData(camera); + for (auto [i, c] : utils::enumerate(*config)) + c.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) +{ + for (auto it : request->buffers()) + completeBuffer(request, it.second); + + request->metadata().set(controls::SensorTimestamp, currentTimestamp()); + completeRequest(request); + + return 0; +} + +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..4df70a13 --- /dev/null +++ b/src/libcamera/pipeline/virtual/virtual.h @@ -0,0 +1,45 @@ +/* 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/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, + const std::vector &supportedResolutions); + + ~VirtualCameraData() = default; + + const std::vector supportedResolutions_; + Size maxResolutionSize_; + Size minResolutionSize_; + + std::vector streamConfigs_; +}; + +} /* namespace libcamera */ From patchwork Mon Sep 30 06:29:45 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Harvey Yang X-Patchwork-Id: 21418 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 9C713C3257 for ; Mon, 30 Sep 2024 06:34:09 +0000 (UTC) Received: from lancelot.ideasonboard.com (localhost [IPv6:::1]) by lancelot.ideasonboard.com (Postfix) with ESMTP id DA10D6351F; Mon, 30 Sep 2024 08:34:08 +0200 (CEST) Authentication-Results: lancelot.ideasonboard.com; dkim=pass (1024-bit key; unprotected) header.d=chromium.org header.i=@chromium.org header.b="X/mWYTXV"; dkim-atps=neutral Received: from mail-oi1-x235.google.com (mail-oi1-x235.google.com [IPv6:2607:f8b0:4864:20::235]) by lancelot.ideasonboard.com (Postfix) with ESMTPS id 720BC63510 for ; Mon, 30 Sep 2024 08:33:56 +0200 (CEST) Received: by mail-oi1-x235.google.com with SMTP id 5614622812f47-3e034fac53bso1797220b6e.3 for ; Sun, 29 Sep 2024 23:33:56 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=chromium.org; s=google; t=1727678035; x=1728282835; 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=VuU4cGIN+faXvAvU9Paf7WKxATqLyOfcBxu4BApn4rU=; b=X/mWYTXV1cr2EJ631St+h44Rt6qv9bKyfmnmEXhlZ6+f4TZKGUBG+rwwg3Zyxaf4Pt lN22XsGiu+Rq2LEq/me6UcoLbfXU5VmzFVDdy+jhaGSbbpcW1wAk6E8X0zmhw5wMC3Q8 O9HcpjMxohjvKFzByz3uqUeVUXfYXWyQG9nqg= X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1727678035; x=1728282835; 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=VuU4cGIN+faXvAvU9Paf7WKxATqLyOfcBxu4BApn4rU=; b=MPGFHjOPkOynKBo1U+1QBTBbNfRXgUqb23Bn3/rwowt7xagFZEqNmBnAbXS1ip/rPE CiX5mCcnyLsqTc/+n9l5uWnHrvBhFHRJdBMyITucbfVnhmY9geo4Z0ciH2eRx6p8hjbU uCvq8t8ql8DDLk8mNOMZeCMaGVwYD3Pu5zWcm7vKBnOV3lyEdcRKmJAHPaGhhQqQeGz1 RQEgE9MouCFgHsbhs8Yj2E7wd62cDeXhy5S/k835srdDK0Q8AE397fZQD3+FhvVD4/Of AU7AxWerDgZ/veVt1yMy1F+sAtG0WwLXUbsoWI3G/T/+u3xD0GUcZyOhTMx5334NK4Y1 Ckdg== X-Gm-Message-State: AOJu0YyaUXkS+JMiai5MDvjfYJHA/EgsiQzaYVusqBg9Ul5gW4yvUjTh jHQp2OXDj9wUd/FFQmIpAsvO3u6MKuQyrRezDncXUZb4h+dRZdW+tqLSQl9CMkDlhhq+4iN3pkA = X-Google-Smtp-Source: AGHT+IE6yzoGzqDi3co52DpWrJU2trLq1s23WaydgrYE4i9Jg5+CPDw82xm+4Cx0nM+bkQgSz2H0zw== X-Received: by 2002:a05:6808:2106:b0:3e2:8c58:6025 with SMTP id 5614622812f47-3e3939e8078mr5566149b6e.43.1727678034625; Sun, 29 Sep 2024 23:33:54 -0700 (PDT) Received: from chenghaoyang-low.c.googlers.com.com (208.158.221.35.bc.googleusercontent.com. [35.221.158.208]) by smtp.gmail.com with ESMTPSA id d2e1a72fcca58-71b265166e2sm5487671b3a.131.2024.09.29.23.33.52 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Sun, 29 Sep 2024 23:33:53 -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 , Jacopo Mondi Subject: [PATCH v14 4/7] libcamera: pipeline: Add test pattern for VirtualPipelineHandler Date: Mon, 30 Sep 2024 06:29:45 +0000 Message-ID: <20240930063342.3014837-5-chenghaoyang@google.com> X-Mailer: git-send-email 2.46.1.824.gd892dcdcdd-goog In-Reply-To: <20240930063342.3014837-1-chenghaoyang@google.com> References: <20240930063342.3014837-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. A shifting mechanism is enabled. For each frame, the image is shifted to the left by 1 pixel. It drops FPS though. 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 Reviewed-by: Jacopo Mondi Reviewed-by: Kieran Bingham --- src/android/meson.build | 19 --- .../pipeline/virtual/frame_generator.h | 29 ++++ src/libcamera/pipeline/virtual/meson.build | 3 + .../virtual/test_pattern_generator.cpp | 137 ++++++++++++++++++ .../pipeline/virtual/test_pattern_generator.h | 53 +++++++ src/libcamera/pipeline/virtual/virtual.cpp | 41 +++++- src/libcamera/pipeline/virtual/virtual.h | 5 + src/meson.build | 19 +++ 8 files changed, 284 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..4ff41dd8 --- /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 int 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..c5a93d37 --- /dev/null +++ b/src/libcamera/pipeline/virtual/test_pattern_generator.cpp @@ -0,0 +1,137 @@ +/* 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 + +namespace libcamera { + +LOG_DECLARE_CATEGORY(Virtual) + +static const unsigned int kARGBSize = 4; + +int 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; + + return 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 */ + } +} + +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 */ + } + } +} + +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..2ff1e40e --- /dev/null +++ b/src/libcamera/pipeline/virtual/test_pattern_generator.h @@ -0,0 +1,53 @@ +/* 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: + int 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: + /* Generate a template buffer of the color bar test pattern. */ + void configure(const Size &size) override; +}; + +class DiagonalLinesGenerator : public TestPatternGenerator +{ +public: + /* 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 d1584f59..2b258492 100644 --- a/src/libcamera/pipeline/virtual/virtual.cpp +++ b/src/libcamera/pipeline/virtual/virtual.cpp @@ -34,6 +34,7 @@ #include "libcamera/internal/camera.h" #include "libcamera/internal/dma_buf_allocator.h" #include "libcamera/internal/formats.h" +#include "libcamera/internal/framebuffer.h" #include "libcamera/internal/pipeline_handler.h" namespace libcamera { @@ -93,6 +94,8 @@ private: return static_cast(camera->_d()); } + void initFrameGenerator(Camera *camera); + DmaBufAllocator dmaBufAllocator_; }; @@ -227,8 +230,10 @@ int PipelineHandlerVirtual::configure(Camera *camera, CameraConfiguration *config) { VirtualCameraData *data = cameraData(camera); - for (auto [i, c] : utils::enumerate(*config)) + for (auto [i, c] : utils::enumerate(*config)) { c.setStream(&data->streamConfigs_[i].stream); + data->streamConfigs_[i].frameGenerator->configure(c.size); + } return 0; } @@ -264,8 +269,24 @@ void PipelineHandlerVirtual::stopDevice([[maybe_unused]] Camera *camera) int PipelineHandlerVirtual::queueRequestDevice([[maybe_unused]] Camera *camera, Request *request) { - for (auto it : request->buffers()) - completeBuffer(request, it.second); + VirtualCameraData *data = cameraData(camera); + + 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; + if (streamConfig.frameGenerator->generateFrame( + stream->configuration().size, buffer)) + buffer->_d()->cancel(); + + completeBuffer(request, buffer); + break; + } + } + ASSERT(found); + } request->metadata().set(controls::SensorTimestamp, currentTimestamp()); completeRequest(request); @@ -307,11 +328,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 4df70a13..9b79ac09 100644 --- a/src/libcamera/pipeline/virtual/virtual.h +++ b/src/libcamera/pipeline/virtual/virtual.h @@ -15,6 +15,8 @@ #include "libcamera/internal/camera.h" #include "libcamera/internal/pipeline_handler.h" +#include "test_pattern_generator.h" + namespace libcamera { class VirtualCameraData : public Camera::Private @@ -28,6 +30,7 @@ public: }; struct StreamConfig { Stream stream; + std::unique_ptr frameGenerator; }; VirtualCameraData(PipelineHandler *pipe, @@ -35,6 +38,8 @@ public: ~VirtualCameraData() = default; + TestPattern testPattern_ = TestPattern::ColorBars; + const std::vector supportedResolutions_; Size maxResolutionSize_; Size minResolutionSize_; 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 Mon Sep 30 06:29:46 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Harvey Yang X-Patchwork-Id: 21419 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 2F46CC3257 for ; Mon, 30 Sep 2024 06:34:13 +0000 (UTC) Received: from lancelot.ideasonboard.com (localhost [IPv6:::1]) by lancelot.ideasonboard.com (Postfix) with ESMTP id 97D6B63522; Mon, 30 Sep 2024 08:34:12 +0200 (CEST) Authentication-Results: lancelot.ideasonboard.com; dkim=pass (1024-bit key; unprotected) header.d=chromium.org header.i=@chromium.org header.b="Rx6kYfnl"; dkim-atps=neutral Received: from mail-ot1-x32d.google.com (mail-ot1-x32d.google.com [IPv6:2607:f8b0:4864:20::32d]) by lancelot.ideasonboard.com (Postfix) with ESMTPS id BFE5363512 for ; Mon, 30 Sep 2024 08:33:58 +0200 (CEST) Received: by mail-ot1-x32d.google.com with SMTP id 46e09a7af769-710daaadd9bso2212774a34.2 for ; Sun, 29 Sep 2024 23:33:58 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=chromium.org; s=google; t=1727678036; x=1728282836; 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=FKROXjaRq7rbZO9SmMn9LKER7xG7vG5xkgDrpVjuMfo=; b=Rx6kYfnl0HnqwAxf/dQXgaGv+ywEIJBUhreglXjVydhRMkZbnoSujTV+BHVFkdZPPK TQaDF6jKZADl+cf90oy3EplC0ADgCHDg+zi/wPGRSXAT1eGppUE24YBtEGbkAFt1EpdE BuvUaIEzZDwxdYI6re5N9o15xG2lNYY+M9Axo= X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1727678036; x=1728282836; 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=FKROXjaRq7rbZO9SmMn9LKER7xG7vG5xkgDrpVjuMfo=; b=mir2OxDLY4Fhp2bMrPp3dp9ykF+/jLPt7+Urp98pcCxeYU6EDLlszvddq1YmXItr4J illVILZtObGSmQHrWz+0G86EywT4xzUC4Kk0J0SO3+NcUX7SrJxtO1fP4cSjaq0KLxzG y49v3OPs6uP8MmcJ6Une7/ChhWcAxxL5PNHakDQNLQ9uiaa4JOyH7ixUJeJHwFbi4jU7 deaKXAuR2Fjcj06b1fWiYVaX05LTdV+Ii0IzUcaYQSw4gthyJ5DHntb5xB/sGuqlII+b M4YLhsPrmuJQewzLL6MdUBKI/KINY4LUBvq0zGhc7rWwfUOPtdVuwrJz+g7tPt3fyaxM F4uA== X-Gm-Message-State: AOJu0Yzljt3/d2+Ns/HJGiNR6bAGn8CqnmCKnKdS6tlIbQD6qvxu6YyM KS7RuCMlkURpJjL3FFT7SRn6Kzv1iuC8X+FPu6ZwN7Rq3a5JpS92Fb4l7agzu0qpIj4I6FGs46E = X-Google-Smtp-Source: AGHT+IGCQcr2ErVt8xJDNYcYG7VTdSbXIpRBORAvdbLdwRRfFWJ+08o5VGrqJu5xIjeeRRp6NMh6CA== X-Received: by 2002:a05:6830:3592:b0:710:fae8:fcae with SMTP id 46e09a7af769-714fbe908cbmr8497296a34.18.1727678036680; Sun, 29 Sep 2024 23:33:56 -0700 (PDT) Received: from chenghaoyang-low.c.googlers.com.com (208.158.221.35.bc.googleusercontent.com. [35.221.158.208]) by smtp.gmail.com with ESMTPSA id d2e1a72fcca58-71b265166e2sm5487671b3a.131.2024.09.29.23.33.54 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Sun, 29 Sep 2024 23:33:56 -0700 (PDT) From: Harvey Yang X-Google-Original-From: Harvey Yang To: libcamera-devel@lists.libcamera.org Cc: Harvey Yang , Konami Shu , Harvey Yang , Yunke Cao , Tomasz Figa , Jacopo Mondi Subject: [PATCH v14 5/7] libcamera: virtual: Add ImageFrameGenerator Date: Mon, 30 Sep 2024 06:29:46 +0000 Message-ID: <20240930063342.3014837-6-chenghaoyang@google.com> X-Mailer: git-send-email 2.46.1.824.gd892dcdcdd-goog In-Reply-To: <20240930063342.3014837-1-chenghaoyang@google.com> References: <20240930063342.3014837-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" 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 Reviewed-by: Jacopo Mondi --- .../virtual/image_frame_generator.cpp | 175 ++++++++++++++++++ .../pipeline/virtual/image_frame_generator.h | 51 +++++ src/libcamera/pipeline/virtual/meson.build | 4 + 3 files changed, 230 insertions(+) create mode 100644 src/libcamera/pipeline/virtual/image_frame_generator.cpp create mode 100644 src/libcamera/pipeline/virtual/image_frame_generator.h 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..a1915b24 --- /dev/null +++ b/src/libcamera/pipeline/virtual/image_frame_generator.cpp @@ -0,0 +1,175 @@ +/* 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 "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; + } + + std::unique_ptr dstY = + std::make_unique(width * height); + std::unique_ptr dstUV = + std::make_unique(width * height / 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 }); + } +} + +int 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 Consider setting the proceed interval in the config file */ + parameter_++; + if (parameter_ % frameInterval == 0) + frameCount_++; + + return 0; +} + +/* + * \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..cd243816 --- /dev/null +++ b/src/libcamera/pipeline/virtual/image_frame_generator.h @@ -0,0 +1,51 @@ +/* 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 { + +/* Frame configuration provided by the config file */ +struct ImageFrames { + std::filesystem::path path; + std::optional number; +}; + +class ImageFrameGenerator : public FrameGenerator +{ +public: + static std::unique_ptr create(ImageFrames &imageFrames); + +private: + static constexpr unsigned int frameInterval = 4; + + struct ImageFrameData { + std::unique_ptr Y; + std::unique_ptr UV; + Size size; + }; + + void configure(const Size &size) override; + int 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 0c537777..bb38c193 100644 --- a/src/libcamera/pipeline/virtual/meson.build +++ b/src/libcamera/pipeline/virtual/meson.build @@ -1,8 +1,12 @@ # SPDX-License-Identifier: CC0-1.0 libcamera_internal_sources += files([ + 'image_frame_generator.cpp', 'test_pattern_generator.cpp', 'virtual.cpp', ]) +libjpeg = dependency('libjpeg', required : true) + libcamera_deps += [libyuv_dep] +libcamera_deps += [libjpeg] From patchwork Mon Sep 30 06:29:47 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Harvey Yang X-Patchwork-Id: 21420 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 70403C32D4 for ; Mon, 30 Sep 2024 06:34:16 +0000 (UTC) Received: from lancelot.ideasonboard.com (localhost [IPv6:::1]) by lancelot.ideasonboard.com (Postfix) with ESMTP id CB2DF6351D; Mon, 30 Sep 2024 08:34:15 +0200 (CEST) Authentication-Results: lancelot.ideasonboard.com; dkim=pass (1024-bit key; unprotected) header.d=chromium.org header.i=@chromium.org header.b="dvhqtayv"; dkim-atps=neutral Received: from mail-pf1-x429.google.com (mail-pf1-x429.google.com [IPv6:2607:f8b0:4864:20::429]) by lancelot.ideasonboard.com (Postfix) with ESMTPS id 498C86351D for ; Mon, 30 Sep 2024 08:34:01 +0200 (CEST) Received: by mail-pf1-x429.google.com with SMTP id d2e1a72fcca58-71b0d9535c0so2747710b3a.2 for ; Sun, 29 Sep 2024 23:34:01 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=chromium.org; s=google; t=1727678039; x=1728282839; 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=ETt7e8f+phGAqYJBfT/GTHoBzkKliDvRsJJ61gFygoE=; b=dvhqtayvgO7VZtFrZoKYUyPuhBh4fnxpF1Ab6iPIMHBhZvBv8TQcMYc2daysknPWGF PtatXmV2F5GxohbbYxm1af5EEZimHMltOsqWYqqZSHlJ8n7aKY2CDGrM0qwUMlKj99Sy Losrkti/yCh/39M8qExH2zTFOfR/B8gsK4n6k= X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1727678039; x=1728282839; 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=ETt7e8f+phGAqYJBfT/GTHoBzkKliDvRsJJ61gFygoE=; b=FwZHUxUD3Esn14YHNK3z2Hlc7o59w5V8RS7jF8WNhiCRr0WWgR/5K15bYIzXXia0dx Y1tnCsJqnQPMEkqRnpuw6DWsqhATw9QRB8oE64vF2VkDVMZ3WczX7mmsKkmqvhDdYBoh kwueu7Ft2b0bucfi4fwYJJlQS+N0EIVEJ4dQDELCzcAc1V0T2dyptW2X3+Mx5/t1IqR2 pboOLObT1pX8qAgCq0cpyKrKKz59qybaWam9+W7irz/s0nmatOUYmF2/5uz4TC3iYxMw rfN2IssvW41Q88SrDipJurxEuVu/1XteruCRH88MmDxZTuEIS1e9VloZnjnmIAmY51MR Xifg== X-Gm-Message-State: AOJu0Yyq3dZst8/kN5j6G9wQ+rfspTaeCy5mMXTZ8KAFGGzQGo0KROL+ LAH4v5ZghbmHru8jrTicmjBvBWsRZwtTzOXEos5FrE4qqA+5fcf+NA0TWXjApWOicMnSHUtNJpw = X-Google-Smtp-Source: AGHT+IHaHqElUusCPUIkL9UA1oaBQqqkRczn9+89oo3XyiE70BfJX+cTGLzQrLm11j/8tembCmP74Q== X-Received: by 2002:a05:6a20:d045:b0:1d5:14ff:a15f with SMTP id adf61e73a8af0-1d514ffa2b8mr6962653637.11.1727678038666; Sun, 29 Sep 2024 23:33:58 -0700 (PDT) Received: from chenghaoyang-low.c.googlers.com.com (208.158.221.35.bc.googleusercontent.com. [35.221.158.208]) by smtp.gmail.com with ESMTPSA id d2e1a72fcca58-71b265166e2sm5487671b3a.131.2024.09.29.23.33.56 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Sun, 29 Sep 2024 23:33:58 -0700 (PDT) From: Harvey Yang X-Google-Original-From: Harvey Yang To: libcamera-devel@lists.libcamera.org Cc: Harvey Yang , Konami Shu , Harvey Yang , Yunke Cao , Tomasz Figa Subject: [PATCH v14 6/7] libcamera: virtual: Read config and register cameras based on the config Date: Mon, 30 Sep 2024 06:29:47 +0000 Message-ID: <20240930063342.3014837-7-chenghaoyang@google.com> X-Mailer: git-send-email 2.46.1.824.gd892dcdcdd-goog In-Reply-To: <20240930063342.3014837-1-chenghaoyang@google.com> References: <20240930063342.3014837-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" 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. In the default config file, only Test Patterns are used. Developers can use real images loading if desired. 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 | 48 ++++ .../pipeline/virtual/data/virtual.yaml | 36 +++ .../virtual/image_frame_generator.cpp | 16 +- .../pipeline/virtual/image_frame_generator.h | 5 +- src/libcamera/pipeline/virtual/meson.build | 1 + src/libcamera/pipeline/virtual/parser.cpp | 260 ++++++++++++++++++ src/libcamera/pipeline/virtual/parser.h | 39 +++ src/libcamera/pipeline/virtual/virtual.cpp | 122 ++++---- src/libcamera/pipeline/virtual/virtual.h | 21 +- 9 files changed, 483 insertions(+), 65 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..b51eb5ac --- /dev/null +++ b/src/libcamera/pipeline/virtual/README.md @@ -0,0 +1,48 @@ +# 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". 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. +- `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. + - `parseFrameGenerator()`: Parses `test_pattern` or `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. +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/image_frame_generator.cpp b/src/libcamera/pipeline/virtual/image_frame_generator.cpp index a1915b24..26ee1a54 100644 --- a/src/libcamera/pipeline/virtual/image_frame_generator.cpp +++ b/src/libcamera/pipeline/virtual/image_frame_generator.cpp @@ -40,15 +40,7 @@ ImageFrameGenerator::create(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"); - + for (std::filesystem::path path : imageFrames.files) { File file(path); if (!file.open(File::OpenModeFlag::ReadOnly)) { LOG(Virtual, Error) << "Failed to open image file " << file.fileName() @@ -88,6 +80,8 @@ ImageFrameGenerator::create(ImageFrames &imageFrames) Size(width, height) }); } + ASSERT(!imageFrameGenerator->imageFrameDatas_.empty()); + return imageFrameGenerator; } @@ -99,7 +93,7 @@ void ImageFrameGenerator::configure(const Size &size) frameCount_ = 0; parameter_ = 0; - for (unsigned int i = 0; i < imageFrames_->number.value_or(1); i++) { + for (unsigned int i = 0; i < imageFrameDatas_.size(); i++) { /* Scale the imageFrameDatas_ to scaledY and scaledUV */ unsigned int halfSizeWidth = (size.width + 1) / 2; unsigned int halfSizeHeight = (size.height + 1) / 2; @@ -135,7 +129,7 @@ int ImageFrameGenerator::generateFrame(const Size &size, const FrameBuffer *buff auto planes = mappedFrameBuffer.planes(); /* Make sure the frameCount does not over the number of images */ - frameCount_ %= imageFrames_->number.value_or(1); + frameCount_ %= imageFrameDatas_.size(); /* Write the scaledY and scaledUV to the mapped frame buffer */ libyuv::NV12Copy(scaledFrameDatas_[frameCount_].Y.get(), size.width, diff --git a/src/libcamera/pipeline/virtual/image_frame_generator.h b/src/libcamera/pipeline/virtual/image_frame_generator.h index cd243816..6e83ab20 100644 --- a/src/libcamera/pipeline/virtual/image_frame_generator.h +++ b/src/libcamera/pipeline/virtual/image_frame_generator.h @@ -10,9 +10,9 @@ #include #include -#include #include #include +#include #include "frame_generator.h" @@ -20,8 +20,7 @@ namespace libcamera { /* Frame configuration provided by the config file */ struct ImageFrames { - std::filesystem::path path; - std::optional number; + std::vector files; }; class ImageFrameGenerator : public FrameGenerator diff --git a/src/libcamera/pipeline/virtual/meson.build b/src/libcamera/pipeline/virtual/meson.build index bb38c193..f3cb80b4 100644 --- a/src/libcamera/pipeline/virtual/meson.build +++ b/src/libcamera/pipeline/virtual/meson.build @@ -2,6 +2,7 @@ libcamera_internal_sources += files([ 'image_frame_generator.cpp', + '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..cc782d12 --- /dev/null +++ b/src/libcamera/pipeline/virtual/parser.cpp @@ -0,0 +1,260 @@ +/* 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->config_.id = cameraId; + ControlInfoMap::Map controls; + /* todo: Check which resolution's frame rate to be reported */ + controls[&controls::FrameDurationLimits] = + 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)); + } + + 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 (parseFrameGenerator(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::parseFrameGenerator(const YamlObject &cameraConfigData, VirtualCameraData *data) +{ + const std::string testPatternKey = "test_pattern"; + const std::string framesKey = "frames"; + if (cameraConfigData.contains(testPatternKey)) { + if (cameraConfigData.contains(framesKey)) { + LOG(Virtual, Error) << "A camera should use either " + << testPatternKey << " or " << framesKey; + return -EINVAL; + } + + auto testPattern = cameraConfigData[testPatternKey].get(""); + + if (testPattern == "bars") { + data->config_.frame = TestPattern::ColorBars; + } else if (testPattern == "lines") { + data->config_.frame = TestPattern::DiagonalLines; + } else { + LOG(Virtual, Debug) << "Test pattern: " << testPattern + << " is not supported"; + return -EINVAL; + } + + return 0; + } + + const YamlObject &frames = cameraConfigData[framesKey]; + + /* When there is no frames provided in the config file, use color bar test pattern */ + if (!frames) { + data->config_.frame = TestPattern::ColorBars; + return 0; + } + + if (!frames.isDictionary()) { + LOG(Virtual, Error) << "'frames' is not a dictionary."; + return -EINVAL; + } + + auto path = frames["path"].get(); + + if (!path) { + LOG(Virtual, Error) << "Test pattern or path should be specified."; + return -EINVAL; + } + + std::vector files; + + switch (std::filesystem::symlink_status(*path).type()) { + case std::filesystem::file_type::regular: + files.push_back(*path); + break; + + case std::filesystem::file_type::directory: + for (const auto &dentry : std::filesystem::directory_iterator{ *path }) { + if (dentry.is_regular_file()) + files.push_back(dentry.path()); + } + + std::sort(files.begin(), files.end(), [](const auto &a, const auto &b) { + return ::strverscmp(a.c_str(), b.c_str()) < 0; + }); + + if (files.empty()) { + LOG(Virtual, Error) << "Directory has no files: " << *path; + return -EINVAL; + } + break; + + default: + LOG(Virtual, Error) << "Frame: " << *path << " is not supported"; + return -EINVAL; + } + + data->config_.frame = ImageFrames{ std::move(files) }; + + 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..6717be31 --- /dev/null +++ b/src/libcamera/pipeline/virtual/parser.h @@ -0,0 +1,39 @@ +/* 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: + 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 parseFrameGenerator(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 2b258492..3c9752c2 100644 --- a/src/libcamera/pipeline/virtual/virtual.cpp +++ b/src/libcamera/pipeline/virtual/virtual.cpp @@ -36,6 +36,9 @@ #include "libcamera/internal/formats.h" #include "libcamera/internal/framebuffer.h" #include "libcamera/internal/pipeline_handler.h" +#include "libcamera/internal/yaml_parser.h" + +#include "parser.h" namespace libcamera { @@ -54,6 +57,13 @@ uint64_t currentTimestamp() } /* namespace */ +template +struct overloaded : Ts... { + using Ts::operator()...; +}; +template +overloaded(Ts...) -> overloaded; + class VirtualCameraConfiguration : public CameraConfiguration { public: @@ -94,7 +104,7 @@ private: return static_cast(camera->_d()); } - void initFrameGenerator(Camera *camera); + bool initFrameGenerator(Camera *camera); DmaBufAllocator dmaBufAllocator_; }; @@ -104,15 +114,19 @@ bool PipelineHandlerVirtual::created_ = false; VirtualCameraData::VirtualCameraData(PipelineHandler *pipe, const std::vector &supportedResolutions) - : Camera::Private(pipe), supportedResolutions_(supportedResolutions) + : Camera::Private(pipe) { - for (const auto &resolution : supportedResolutions_) { - if (minResolutionSize_.isNull() || minResolutionSize_ > resolution.size) - minResolutionSize_ = resolution.size; + config_.resolutions = 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(config_.maxResolutionSize) }); + /* \todo Support multiple streams and pass multi_stream_test */ streamConfigs_.resize(kMaxStream); } @@ -139,7 +153,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; @@ -154,7 +168,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; } @@ -210,12 +224,12 @@ PipelineHandlerVirtual::generateConfiguration(Camera *camera, 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; config->addConfiguration(cfg); @@ -232,6 +246,7 @@ int PipelineHandlerVirtual::configure(Camera *camera, VirtualCameraData *data = cameraData(camera); for (auto [i, c] : utils::enumerate(*config)) { c.setStream(&data->streamConfigs_[i].stream); + /* Start reading the images/generating test patterns */ data->streamConfigs_[i].frameGenerator->configure(c.size); } @@ -301,50 +316,65 @@ 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); - - /* Create and register the camera. */ - std::set streams; - for (auto &streamConfig : data->streamConfigs_) - streams.insert(&streamConfig.stream); + 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; + } - const std::string id = "Virtual0"; - std::shared_ptr camera = Camera::create(std::move(data), id, streams); + 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; + } - initFrameGenerator(camera.get()); + /* 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->config_.id; + std::shared_ptr camera = Camera::create(std::move(data), id, streams); + + if (!initFrameGenerator(camera.get())) { + LOG(Virtual, Error) << "Failed to initialize frame " + << "generator for camera: " << id; + continue; + } - registerCamera(std::move(camera)); + registerCamera(std::move(camera)); + } 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 9b79ac09..5ac0942b 100644 --- a/src/libcamera/pipeline/virtual/virtual.h +++ b/src/libcamera/pipeline/virtual/virtual.h @@ -7,6 +7,8 @@ #pragma once +#include +#include #include #include @@ -15,10 +17,14 @@ #include "libcamera/internal/camera.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: @@ -32,17 +38,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, const std::vector &supportedResolutions); ~VirtualCameraData() = default; - TestPattern testPattern_ = TestPattern::ColorBars; - - const std::vector supportedResolutions_; - Size maxResolutionSize_; - Size minResolutionSize_; + Configuration config_; std::vector streamConfigs_; }; From patchwork Mon Sep 30 06:29:48 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Harvey Yang X-Patchwork-Id: 21421 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 C17CAC3257 for ; Mon, 30 Sep 2024 06:34:19 +0000 (UTC) Received: from lancelot.ideasonboard.com (localhost [IPv6:::1]) by lancelot.ideasonboard.com (Postfix) with ESMTP id 2473C63518; Mon, 30 Sep 2024 08:34:19 +0200 (CEST) Authentication-Results: lancelot.ideasonboard.com; dkim=pass (1024-bit key; unprotected) header.d=chromium.org header.i=@chromium.org header.b="QO//nQc+"; dkim-atps=neutral Received: from mail-pf1-x436.google.com (mail-pf1-x436.google.com [IPv6:2607:f8b0:4864:20::436]) by lancelot.ideasonboard.com (Postfix) with ESMTPS id 4AC046351A for ; Mon, 30 Sep 2024 08:34:03 +0200 (CEST) Received: by mail-pf1-x436.google.com with SMTP id d2e1a72fcca58-7179069d029so2803730b3a.2 for ; Sun, 29 Sep 2024 23:34:03 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=chromium.org; s=google; t=1727678040; x=1728282840; 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=J+YuiKlLl25i31fSj+za+H/da90SiNNuNEdDtImyhDk=; b=QO//nQc+PGqX4GZ8UdPZsrNJEFIU69mFjDKYhZodW3BVt4iFY3GHm+Q+Q/1nTQbner vlNNqUTahsmSUhGmpHGWBnMUwZhLE6FlvollOfePhDPGmVD5biJeVzlT1+QKX8x96cxh OwsSztIhJM6W4M13qoIvCXNiKRWqAw94EtO+c= X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1727678040; x=1728282840; 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=J+YuiKlLl25i31fSj+za+H/da90SiNNuNEdDtImyhDk=; b=lL7NW8MuX2scde1GByD48ORnBpj1vYthmODjqaS3DwwWc21Ai6ZtCq8UBOc/ExfqqN 6DofAc6kq5N91eRDqlHhfhViLzkHgDL+bIWtb+3bZkJn1zAQAoKfbGEvYXo5dTV0s/C2 fpZylh12rDpAKGu9U5AB7DPSpXKeCOAT40H4H4EUjRDq/AbBt3oRW1bqgldHhXJv7EZa +XzzDGl3ncPe5C9L87BCe5X5wmzgIh0clZgrNfeMr2btNPaRO5R3tft/urCdJomU5pV+ JR4SLfc2H+BR9CuUbcQnrnjZAtx5ZIekAdqCMfPWc1bY1ipY1PkfCSFinI0+RnM8uf90 UUlg== X-Gm-Message-State: AOJu0YxQdmePePqRevlqD8Ool8GXGTjWLW9Q+w3HuajgsmaMF13BLLHS WVMQU52jEXjTUrQ9tK3/xBeBOxDPgfzm/nFKAIrArufPgMzmLgfJUWKtcWJvVft/YWDZJoyR8H4 = X-Google-Smtp-Source: AGHT+IH9C5HYiRDO8u5uOFieQ/GKCoYmbpYsHp57ZgxaMzkutq+0/ChroRieW/JboAY+1Vzr21A36w== X-Received: by 2002:a05:6a00:181d:b0:717:8eca:95 with SMTP id d2e1a72fcca58-71b2604919emr19214639b3a.17.1727678040438; Sun, 29 Sep 2024 23:34:00 -0700 (PDT) Received: from chenghaoyang-low.c.googlers.com.com (208.158.221.35.bc.googleusercontent.com. [35.221.158.208]) by smtp.gmail.com with ESMTPSA id d2e1a72fcca58-71b265166e2sm5487671b3a.131.2024.09.29.23.33.58 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Sun, 29 Sep 2024 23:33:59 -0700 (PDT) From: Harvey Yang X-Google-Original-From: Harvey Yang To: libcamera-devel@lists.libcamera.org Cc: Harvey Yang , Harvey Yang , Milan Zamazal , Kieran Bingham Subject: [PATCH v14 7/7] libcamera: software_isp: Refactor SoftwareIsp to use DmaBufAllocator::exportBuffers Date: Mon, 30 Sep 2024 06:29:48 +0000 Message-ID: <20240930063342.3014837-8-chenghaoyang@google.com> X-Mailer: git-send-email 2.46.1.824.gd892dcdcdd-goog In-Reply-To: <20240930063342.3014837-1-chenghaoyang@google.com> References: <20240930063342.3014837-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); } /**