Show a patch.

GET /api/1.1/patches/8756/?format=api
HTTP 200 OK
Allow: GET, PUT, PATCH, HEAD, OPTIONS
Content-Type: application/json
Vary: Accept

{
    "id": 8756,
    "url": "https://patchwork.libcamera.org/api/1.1/patches/8756/?format=api",
    "web_url": "https://patchwork.libcamera.org/patch/8756/",
    "project": {
        "id": 1,
        "url": "https://patchwork.libcamera.org/api/1.1/projects/1/?format=api",
        "name": "libcamera",
        "link_name": "libcamera",
        "list_id": "libcamera_core",
        "list_email": "libcamera-devel@lists.libcamera.org",
        "web_url": "",
        "scm_url": "",
        "webscm_url": ""
    },
    "msgid": "<20200713084727.232422-7-naush@raspberrypi.com>",
    "date": "2020-07-13T08:47:25",
    "name": "[libcamera-devel,6/9] libcamera: pipeline: raspberrypi: Rework stream buffer logic for zero-copy",
    "commit_ref": null,
    "pull_url": null,
    "state": "superseded",
    "archived": false,
    "hash": "187892a5d349605f39a23e6db9cb3e3d277eea6e",
    "submitter": {
        "id": 34,
        "url": "https://patchwork.libcamera.org/api/1.1/people/34/?format=api",
        "name": "Naushir Patuck",
        "email": "naush@raspberrypi.com"
    },
    "delegate": null,
    "mbox": "https://patchwork.libcamera.org/patch/8756/mbox/",
    "series": [
        {
            "id": 1100,
            "url": "https://patchwork.libcamera.org/api/1.1/series/1100/?format=api",
            "web_url": "https://patchwork.libcamera.org/project/libcamera/list/?series=1100",
            "date": "2020-07-13T08:47:18",
            "name": "Zero-copy RAW stream work",
            "version": 1,
            "mbox": "https://patchwork.libcamera.org/series/1100/mbox/"
        }
    ],
    "comments": "https://patchwork.libcamera.org/api/patches/8756/comments/",
    "check": "pending",
    "checks": "https://patchwork.libcamera.org/api/patches/8756/checks/",
    "tags": {},
    "headers": {
        "Return-Path": "<libcamera-devel-bounces@lists.libcamera.org>",
        "X-Original-To": "parsemail@patchwork.libcamera.org",
        "Delivered-To": "parsemail@patchwork.libcamera.org",
        "Received": [
            "from lancelot.ideasonboard.com (lancelot.ideasonboard.com\n\t[92.243.16.209])\n\tby patchwork.libcamera.org (Postfix) with ESMTPS id 6128EBDB1C\n\tfor <parsemail@patchwork.libcamera.org>;\n\tMon, 13 Jul 2020 08:48:06 +0000 (UTC)",
            "from lancelot.ideasonboard.com (localhost [IPv6:::1])\n\tby lancelot.ideasonboard.com (Postfix) with ESMTP id 2B18D605BD;\n\tMon, 13 Jul 2020 10:48:06 +0200 (CEST)",
            "from mail-wr1-x430.google.com (mail-wr1-x430.google.com\n\t[IPv6:2a00:1450:4864:20::430])\n\tby lancelot.ideasonboard.com (Postfix) with ESMTPS id D5B98605B2\n\tfor <libcamera-devel@lists.libcamera.org>;\n\tMon, 13 Jul 2020 10:48:04 +0200 (CEST)",
            "by mail-wr1-x430.google.com with SMTP id r12so14993621wrj.13\n\tfor <libcamera-devel@lists.libcamera.org>;\n\tMon, 13 Jul 2020 01:48:04 -0700 (PDT)",
            "from naushir-VirtualBox.patuck.local ([88.97.76.4])\n\tby smtp.gmail.com with ESMTPSA id\n\tg14sm23203357wrm.93.2020.07.13.01.48.02\n\t(version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256);\n\tMon, 13 Jul 2020 01:48:02 -0700 (PDT)"
        ],
        "Authentication-Results": "lancelot.ideasonboard.com;\n\tdkim=fail reason=\"signature verification failed\" (2048-bit key;\n\tunprotected) header.d=raspberrypi.com header.i=@raspberrypi.com\n\theader.b=\"dyz7GIuw\"; dkim-atps=neutral",
        "DKIM-Signature": "v=1; a=rsa-sha256; c=relaxed/relaxed;\n\td=raspberrypi.com; s=google;\n\th=from:to:cc:subject:date:message-id:in-reply-to:references\n\t:mime-version:content-transfer-encoding;\n\tbh=Flrmqvsok2P/t2kYp3nlCT1qzUXZizkhVcFIG6UCXWs=;\n\tb=dyz7GIuwxfXq2AZjgSQGsHq65SmCnAP1kbU7wMhSiw2gPa7CDvtRkzi3xlWV3hQPRa\n\t1M9tKVWQ1OtVOK57g9BZZdWUxo5TS7k+BlGUbUaO/zb4a4JLCkJb6FS77sgVpB3srxgh\n\tXbwDE4DR8QzlvquG5eetmKaVifvUZf/KdjQP6BkKNzFTm1wWQggvNCaL6YSsL2llEIsi\n\teTVTTbk73aGNY418bR9281oHt9soub8ZF/2EC+0f6vjeQN2jJ6N5/CBgHqjyfofhkNI8\n\t6oR5cM0HYi+GGx1sen48g5VOWRzbp8rG4EgbeZPLrUGCv1MLM3/jXdcOYJpCBmIHZI0H\n\tDxDw==",
        "X-Google-DKIM-Signature": "v=1; a=rsa-sha256; c=relaxed/relaxed;\n\td=1e100.net; s=20161025;\n\th=x-gm-message-state:from:to:cc:subject:date:message-id:in-reply-to\n\t:references:mime-version:content-transfer-encoding;\n\tbh=Flrmqvsok2P/t2kYp3nlCT1qzUXZizkhVcFIG6UCXWs=;\n\tb=PXscPWLIgMY8BS0XCysgnDGcp/V0SI3s3MN0F9KWkTwah1iohB+73Zchf133zq5O2t\n\tKOeDqFjOx5XkVPsl4bNHBCLSWEnGCV65dyS4dbKUvb2jzAkR9wJd8QrTc00mdogEeCi6\n\tYAQ4eAhCDzXnoVchIrFlDwuYf+UHo0vkeRIVxxYtcaWn/VI4V+tZJsoB8zKxrGXBFzjy\n\t5uTq29d7MdXrneXSr55QlT7RWfs0S4WoBmpTQeyJh4vUUuLEcn+84w4k8M05Hz/NSD66\n\tlpSS/a88NSO39Mw8PNpz+//F63B+RNhoE2IE2EwA7yP1rqM80YxqMe1YkS+3+igpbAEM\n\tDrmw==",
        "X-Gm-Message-State": "AOAM530Jl3F+KJk+u6GqwXkJ17krXXMH5rsUIFR80AxaRW4wznkdEvva\n\tgiasAinDreHlbuH1AMz0uUbb66Fuq2I=",
        "X-Google-Smtp-Source": "ABdhPJzg4Yo5Axoxy6CEaLZza4poGevnNs7BoTLeXr5VrekpGnegjMO9ZOnzc8rVSevPPsjZfiLdUg==",
        "X-Received": "by 2002:adf:9148:: with SMTP id\n\tj66mr75538756wrj.311.1594630083585; \n\tMon, 13 Jul 2020 01:48:03 -0700 (PDT)",
        "From": "Naushir Patuck <naush@raspberrypi.com>",
        "To": "libcamera-devel@lists.libcamera.org",
        "Date": "Mon, 13 Jul 2020 09:47:25 +0100",
        "Message-Id": "<20200713084727.232422-7-naush@raspberrypi.com>",
        "X-Mailer": "git-send-email 2.25.1",
        "In-Reply-To": "<20200713084727.232422-1-naush@raspberrypi.com>",
        "References": "<20200713084727.232422-1-naush@raspberrypi.com>",
        "MIME-Version": "1.0",
        "Subject": "[libcamera-devel] [PATCH 6/9] libcamera: pipeline: raspberrypi:\n\tRework stream buffer logic for zero-copy",
        "X-BeenThere": "libcamera-devel@lists.libcamera.org",
        "X-Mailman-Version": "2.1.29",
        "Precedence": "list",
        "List-Id": "<libcamera-devel.lists.libcamera.org>",
        "List-Unsubscribe": "<https://lists.libcamera.org/options/libcamera-devel>,\n\t<mailto:libcamera-devel-request@lists.libcamera.org?subject=unsubscribe>",
        "List-Archive": "<https://lists.libcamera.org/pipermail/libcamera-devel/>",
        "List-Post": "<mailto:libcamera-devel@lists.libcamera.org>",
        "List-Help": "<mailto:libcamera-devel-request@lists.libcamera.org?subject=help>",
        "List-Subscribe": "<https://lists.libcamera.org/listinfo/libcamera-devel>,\n\t<mailto:libcamera-devel-request@lists.libcamera.org?subject=subscribe>",
        "Content-Type": "text/plain; charset=\"us-ascii\"",
        "Content-Transfer-Encoding": "7bit",
        "Errors-To": "libcamera-devel-bounces@lists.libcamera.org",
        "Sender": "\"libcamera-devel\" <libcamera-devel-bounces@lists.libcamera.org>"
    },
    "content": "Stop using v4l2_videodevice::allocateBuffer() for internal buffers and\ninstead export/import all buffers. This allows the pipeline to return\nany stream buffer requested by the application as zero-copy.\n\nAdvertise the Unicam Image stream as the RAW capture stream now.\n\nThe RPiStream object now maintains a new list of buffers that are\navailable to queue into a device. This is needed to distinguish between\nFrameBuffers allocated for internal use vs externally provided buffers.\nWhen a Request comes in, if a buffer is not provided for an exported\nstream, we re-use a buffer from this list.\n\nSigned-off-by: Naushir Patuck <naush@raspberrypi.com>\n---\n .../pipeline/raspberrypi/raspberrypi.cpp      | 181 ++++++++----------\n .../pipeline/raspberrypi/rpi_stream.h         | 136 +++++++++----\n 2 files changed, 179 insertions(+), 138 deletions(-)",
    "diff": "diff --git a/src/libcamera/pipeline/raspberrypi/raspberrypi.cpp b/src/libcamera/pipeline/raspberrypi/raspberrypi.cpp\nindex 2f4255a4..f7e16a6c 100644\n--- a/src/libcamera/pipeline/raspberrypi/raspberrypi.cpp\n+++ b/src/libcamera/pipeline/raspberrypi/raspberrypi.cpp\n@@ -200,7 +200,8 @@ private:\n \tvoid checkRequestCompleted();\n \tvoid tryRunPipeline();\n \tvoid tryFlushQueues();\n-\tFrameBuffer *updateQueue(std::queue<FrameBuffer *> &q, uint64_t timestamp, V4L2VideoDevice *dev);\n+\tFrameBuffer *updateQueue(std::queue<FrameBuffer *> &q, uint64_t timestamp,\n+\t\t\t\t RPi::RPiStream *stream);\n \n \tunsigned int ispOutputCount_;\n };\n@@ -523,8 +524,15 @@ int PipelineHandlerRPi::configure(Camera *camera, CameraConfiguration *config)\n \t\tStreamConfiguration &cfg = config->at(i);\n \n \t\tif (isRaw(cfg.pixelFormat)) {\n-\t\t\tcfg.setStream(&data->isp_[Isp::Input]);\n-\t\t\tdata->isp_[Isp::Input].setExternal(true);\n+\t\t\tcfg.setStream(&data->unicam_[Unicam::Image]);\n+\t\t\t/*\n+\t\t\t * We must set both Unicam streams as external, even\n+\t\t\t * though the application may only request RAW frames.\n+\t\t\t * This is because we match timestamps on both streams\n+\t\t\t * to synchronise buffers.\n+\t\t\t */\n+\t\t\tdata->unicam_[Unicam::Image].setExternal(true);\n+\t\t\tdata->unicam_[Unicam::Embedded].setExternal(true);\n \t\t\tcontinue;\n \t\t}\n \n@@ -718,14 +726,13 @@ int PipelineHandlerRPi::queueRequestDevice(Camera *camera, Request *request)\n \tif (data->state_ == RPiCameraData::State::Stopped)\n \t\treturn -EINVAL;\n \n-\t/* Ensure all external streams have associated buffers! */\n-\tfor (auto &stream : data->isp_) {\n-\t\tif (!stream.isExternal())\n-\t\t\tcontinue;\n+\tLOG(RPI, Debug) << \"queueRequestDevice: New request.\";\n \n-\t\tif (!request->findBuffer(&stream)) {\n-\t\t\tLOG(RPI, Error) << \"Attempt to queue request with invalid stream.\";\n-\t\t\treturn -ENOENT;\n+\t/* Push all buffers supplied in the Request to the respective streams. */\n+\tfor (auto stream : data->streams_) {\n+\t\tif (stream->isExternal()) {\n+\t\t\tFrameBuffer *buffer = request->findBuffer(stream);\n+\t\t\tstream->queueBuffer(data->dropFrameCount_ ? nullptr : buffer);\n \t\t}\n \t}\n \n@@ -814,12 +821,10 @@ bool PipelineHandlerRPi::match(DeviceEnumerator *enumerator)\n \t/* Initialize the camera properties. */\n \tdata->properties_ = data->sensor_->properties();\n \n-\t/*\n-\t * List the available output streams.\n-\t * Currently cannot do Unicam streams!\n-\t */\n+\t/*List the available streams an application may request. */\n \tstd::set<Stream *> streams;\n-\tstreams.insert(&data->isp_[Isp::Input]);\n+\tstreams.insert(&data->unicam_[Unicam::Image]);\n+\tstreams.insert(&data->unicam_[Unicam::Embedded]);\n \tstreams.insert(&data->isp_[Isp::Output0]);\n \tstreams.insert(&data->isp_[Isp::Output1]);\n \tstreams.insert(&data->isp_[Isp::Stats]);\n@@ -896,7 +901,7 @@ int PipelineHandlerRPi::queueAllBuffers(Camera *camera)\n \tint ret;\n \n \tfor (auto const stream : data->streams_) {\n-\t\tret = stream->queueBuffers();\n+\t\tret = stream->queueAllBuffers();\n \t\tif (ret < 0)\n \t\t\treturn ret;\n \t}\n@@ -912,7 +917,8 @@ int PipelineHandlerRPi::prepareBuffers(Camera *camera)\n \t/*\n \t * Decide how many internal buffers to allocate. For now, simply look\n \t * at how many external buffers will be provided. Will need to improve\n-\t * this logic.\n+\t * this logic. However, we really must have all stream allocate the same\n+\t * number of buffers to simplify error handling in queueRequestDevice().\n \t */\n \tunsigned int maxBuffers = 0;\n \tfor (const Stream *s : camera->streams())\n@@ -920,33 +926,9 @@ int PipelineHandlerRPi::prepareBuffers(Camera *camera)\n \t\t\tmaxBuffers = std::max(maxBuffers, s->configuration().bufferCount);\n \n \tfor (auto const stream : data->streams_) {\n-\t\tif (stream->isExternal() || stream->isImporter()) {\n-\t\t\t/*\n-\t\t\t * If a stream is marked as external reserve memory to\n-\t\t\t * prepare to import as many buffers are requested in\n-\t\t\t * the stream configuration.\n-\t\t\t *\n-\t\t\t * If a stream is an internal stream with importer\n-\t\t\t * role, reserve as many buffers as possible.\n-\t\t\t */\n-\t\t\tunsigned int count = stream->isExternal()\n-\t\t\t\t\t\t     ? stream->configuration().bufferCount\n-\t\t\t\t\t\t     : maxBuffers;\n-\t\t\tret = stream->importBuffers(count);\n-\t\t\tif (ret < 0)\n-\t\t\t\treturn ret;\n-\t\t} else {\n-\t\t\t/*\n-\t\t\t * If the stream is an internal exporter allocate and\n-\t\t\t * export as many buffers as possible to its internal\n-\t\t\t * pool.\n-\t\t\t */\n-\t\t\tret = stream->allocateBuffers(maxBuffers);\n-\t\t\tif (ret < 0) {\n-\t\t\t\tfreeBuffers(camera);\n-\t\t\t\treturn ret;\n-\t\t\t}\n-\t\t}\n+\t\tret = stream->prepareBuffers(maxBuffers);\n+\t\tif (ret < 0)\n+\t\t\treturn ret;\n \t}\n \n \t/*\n@@ -954,7 +936,7 @@ int PipelineHandlerRPi::prepareBuffers(Camera *camera)\n \t * the IPA and RPI_IPA_EVENT_SIGNAL_ISP_PREPARE event.\n \t */\n \tcount = 0;\n-\tfor (auto const &b : *data->unicam_[Unicam::Image].getBuffers()) {\n+\tfor (auto const &b : data->unicam_[Unicam::Image].getBuffers()) {\n \t\tb->setCookie(count++);\n \t}\n \n@@ -963,14 +945,14 @@ int PipelineHandlerRPi::prepareBuffers(Camera *camera)\n \t * the IPA.\n \t */\n \tcount = 0;\n-\tfor (auto const &b : *data->isp_[Isp::Stats].getBuffers()) {\n+\tfor (auto const &b : data->isp_[Isp::Stats].getBuffers()) {\n \t\tb->setCookie(count++);\n \t\tdata->ipaBuffers_.push_back({ .id = RPiIpaMask::STATS | b->cookie(),\n \t\t\t\t\t      .planes = b->planes() });\n \t}\n \n \tcount = 0;\n-\tfor (auto const &b : *data->unicam_[Unicam::Embedded].getBuffers()) {\n+\tfor (auto const &b : data->unicam_[Unicam::Embedded].getBuffers()) {\n \t\tb->setCookie(count++);\n \t\tdata->ipaBuffers_.push_back({ .id = RPiIpaMask::EMBEDDED_DATA | b->cookie(),\n \t\t\t\t\t      .planes = b->planes() });\n@@ -1081,7 +1063,7 @@ void RPiCameraData::queueFrameAction(unsigned int frame, const IPAOperationData\n \tswitch (action.operation) {\n \tcase RPI_IPA_ACTION_STATS_METADATA_COMPLETE: {\n \t\tunsigned int bufferId = action.data[0];\n-\t\tFrameBuffer *buffer = isp_[Isp::Stats].getBuffers()->at(bufferId).get();\n+\t\tFrameBuffer *buffer = isp_[Isp::Stats].getBuffers().at(bufferId);\n \n \t\thandleStreamBuffer(buffer, &isp_[Isp::Stats]);\n \t\t/* Fill the Request metadata buffer with what the IPA has provided */\n@@ -1092,19 +1074,19 @@ void RPiCameraData::queueFrameAction(unsigned int frame, const IPAOperationData\n \n \tcase RPI_IPA_ACTION_EMBEDDED_COMPLETE: {\n \t\tunsigned int bufferId = action.data[0];\n-\t\tFrameBuffer *buffer = unicam_[Unicam::Embedded].getBuffers()->at(bufferId).get();\n+\t\tFrameBuffer *buffer = unicam_[Unicam::Embedded].getBuffers().at(bufferId);\n \t\thandleStreamBuffer(buffer, &unicam_[Unicam::Embedded]);\n \t\tbreak;\n \t}\n \n \tcase RPI_IPA_ACTION_RUN_ISP: {\n \t\tunsigned int bufferId = action.data[0];\n-\t\tFrameBuffer *buffer = unicam_[Unicam::Image].getBuffers()->at(bufferId).get();\n+\t\tFrameBuffer *buffer = unicam_[Unicam::Image].getBuffers().at(bufferId);\n \n \t\tLOG(RPI, Debug) << \"Input re-queue to ISP, buffer id \" << buffer->cookie()\n \t\t\t\t<< \", timestamp: \" << buffer->metadata().timestamp;\n \n-\t\tisp_[Isp::Input].dev()->queueBuffer(buffer);\n+\t\tisp_[Isp::Input].queueBuffer(buffer);\n \t\tispOutputCount_ = 0;\n \t\tbreak;\n \t}\n@@ -1205,7 +1187,12 @@ void RPiCameraData::ispOutputDequeue(FrameBuffer *buffer)\n \t\t\t<< \", buffer id \" << buffer->cookie()\n \t\t\t<< \", timestamp: \" << buffer->metadata().timestamp;\n \n-\thandleStreamBuffer(buffer, stream);\n+\t/*\n+\t * ISP statistics buffer must not be re-queued or sent back to the\n+\t * application until after the IPA signals so.\n+\t */\n+\tif (stream != &isp_[Isp::Stats])\n+\t\thandleStreamBuffer(buffer, stream);\n \n \t/*\n \t * Increment the number of ISP outputs generated.\n@@ -1233,8 +1220,12 @@ void RPiCameraData::clearIncompleteRequests()\n \t */\n \tfor (auto const request : requestQueue_) {\n \t\tfor (auto const stream : streams_) {\n-\t\t\tif (stream->isExternal())\n-\t\t\t\tstream->dev()->queueBuffer(request->findBuffer(stream));\n+\t\t\tif (!stream->isExternal())\n+\t\t\t\tcontinue;\n+\n+\t\t\tFrameBuffer *buffer = request->findBuffer(stream);\n+\t\t\tif (buffer)\n+\t\t\t\tstream->queueBuffer(buffer);\n \t\t}\n \t}\n \n@@ -1263,7 +1254,7 @@ void RPiCameraData::clearIncompleteRequests()\n \t\t\t * Has the buffer already been handed back to the\n \t\t\t * request? If not, do so now.\n \t\t\t */\n-\t\t\tif (buffer->request())\n+\t\t\tif (buffer && buffer->request())\n \t\t\t\tpipe_->completeBuffer(camera_, request, buffer);\n \t\t}\n \n@@ -1275,30 +1266,24 @@ void RPiCameraData::clearIncompleteRequests()\n void RPiCameraData::handleStreamBuffer(FrameBuffer *buffer, RPi::RPiStream *stream)\n {\n \tif (stream->isExternal()) {\n-\t\tif (!dropFrameCount_) {\n-\t\t\tRequest *request = buffer->request();\n+\t\tRequest *request = requestQueue_.front();\n+\n+\t\tif (!dropFrameCount_ && request->findBuffer(stream) == buffer) {\n+\t\t\t/*\n+\t\t\t * Tag the buffer as completed, returning it to the\n+\t\t\t * application.\n+\t\t\t */\n \t\t\tpipe_->completeBuffer(camera_, request, buffer);\n+\t\t} else {\n+\t\t\t/*\n+\t\t\t * This buffer was not part of the Request, so we can\n+\t\t\t * recycle it.\n+\t\t\t */\n+\t\t\tstream->returnBuffer(buffer);\n \t\t}\n \t} else {\n-\t\t/* Special handling for RAW buffer Requests.\n-\t\t *\n-\t\t * The ISP input stream is alway an import stream, but if the\n-\t\t * current Request has been made for a buffer on the stream,\n-\t\t * simply memcpy to the Request buffer and requeue back to the\n-\t\t * device.\n-\t\t */\n-\t\tif (stream == &unicam_[Unicam::Image] && !dropFrameCount_) {\n-\t\t\tconst Stream *rawStream = static_cast<const Stream *>(&isp_[Isp::Input]);\n-\t\t\tRequest *request = requestQueue_.front();\n-\t\t\tFrameBuffer *raw = request->findBuffer(const_cast<Stream *>(rawStream));\n-\t\t\tif (raw) {\n-\t\t\t\traw->copyFrom(buffer);\n-\t\t\t\tpipe_->completeBuffer(camera_, request, raw);\n-\t\t\t}\n-\t\t}\n-\n-\t\t/* Simply requeue the buffer. */\n-\t\tstream->dev()->queueBuffer(buffer);\n+\t\t/* Simply re-queue the buffer to the requested stream. */\n+\t\tstream->queueBuffer(buffer);\n \t}\n }\n \n@@ -1382,7 +1367,7 @@ void RPiCameraData::tryRunPipeline()\n \t * current bayer buffer will be removed and re-queued to the driver.\n \t */\n \tembeddedBuffer = updateQueue(embeddedQueue_, bayerBuffer->metadata().timestamp,\n-\t\t\t\t     unicam_[Unicam::Embedded].dev());\n+\t\t\t\t     &unicam_[Unicam::Embedded]);\n \n \tif (!embeddedBuffer) {\n \t\tLOG(RPI, Debug) << \"Could not find matching embedded buffer\";\n@@ -1401,7 +1386,7 @@ void RPiCameraData::tryRunPipeline()\n \n \t\tembeddedBuffer = embeddedQueue_.front();\n \t\tbayerBuffer = updateQueue(bayerQueue_, embeddedBuffer->metadata().timestamp,\n-\t\t\t\t\t  unicam_[Unicam::Image].dev());\n+\t\t\t\t\t  &unicam_[Unicam::Image]);\n \n \t\tif (!bayerBuffer) {\n \t\t\tLOG(RPI, Debug) << \"Could not find matching bayer buffer - ending.\";\n@@ -1409,11 +1394,7 @@ void RPiCameraData::tryRunPipeline()\n \t\t}\n \t}\n \n-\t/*\n-\t * Take the first request from the queue and action the IPA.\n-\t * Unicam buffers for the request have already been queued as they come\n-\t * in.\n-\t */\n+\t/* Take the first request from the queue and action the IPA. */\n \tRequest *request = requestQueue_.front();\n \n \t/*\n@@ -1425,12 +1406,6 @@ void RPiCameraData::tryRunPipeline()\n \top.controls = { request->controls() };\n \tipa_->processEvent(op);\n \n-\t/* Queue up any ISP buffers passed into the request. */\n-\tfor (auto &stream : isp_) {\n-\t\tif (stream.isExternal())\n-\t\t\tstream.dev()->queueBuffer(request->findBuffer(&stream));\n-\t}\n-\n \t/* Ready to use the buffers, pop them off the queue. */\n \tbayerQueue_.pop();\n \tembeddedQueue_.pop();\n@@ -1460,32 +1435,42 @@ void RPiCameraData::tryFlushQueues()\n \t * and give a chance for the hardware to return to lock-step. We do have\n \t * to drop all interim frames.\n \t */\n-\tif (unicam_[Unicam::Image].getBuffers()->size() == bayerQueue_.size() &&\n-\t    unicam_[Unicam::Embedded].getBuffers()->size() == embeddedQueue_.size()) {\n+\tif (unicam_[Unicam::Image].getBuffers().size() == bayerQueue_.size() &&\n+\t    unicam_[Unicam::Embedded].getBuffers().size() == embeddedQueue_.size()) {\n+\t\t/* This cannot happen when Unicam streams are external. */\n+\t\tassert(!unicam_[Unicam::Image].isExternal());\n+\n \t\tLOG(RPI, Warning) << \"Flushing all buffer queues!\";\n \n \t\twhile (!bayerQueue_.empty()) {\n-\t\t\tunicam_[Unicam::Image].dev()->queueBuffer(bayerQueue_.front());\n+\t\t\tunicam_[Unicam::Image].queueBuffer(bayerQueue_.front());\n \t\t\tbayerQueue_.pop();\n \t\t}\n \n \t\twhile (!embeddedQueue_.empty()) {\n-\t\t\tunicam_[Unicam::Embedded].dev()->queueBuffer(embeddedQueue_.front());\n+\t\t\tunicam_[Unicam::Embedded].queueBuffer(embeddedQueue_.front());\n \t\t\tembeddedQueue_.pop();\n \t\t}\n \t}\n }\n \n FrameBuffer *RPiCameraData::updateQueue(std::queue<FrameBuffer *> &q, uint64_t timestamp,\n-\t\t\t\t\tV4L2VideoDevice *dev)\n+\t\t\t\t\tRPi::RPiStream *stream)\n {\n+\t/*\n+\t * If the unicam streams are external (both have to the same), then we\n+\t * can only return out the top buffer in the queue, and assume they have\n+\t * been synced by queuing at the same time. We cannot drop these frames,\n+\t * as they may have been provided externally.\n+\t */\n \twhile (!q.empty()) {\n \t\tFrameBuffer *b = q.front();\n-\t\tif (b->metadata().timestamp < timestamp) {\n+\t\tif (!stream->isExternal() && b->metadata().timestamp < timestamp) {\n \t\t\tq.pop();\n-\t\t\tdev->queueBuffer(b);\n-\t\t\tLOG(RPI, Warning) << \"Dropping input frame!\";\n-\t\t} else if (b->metadata().timestamp == timestamp) {\n+\t\t\tstream->queueBuffer(b);\n+\t\t\tLOG(RPI, Warning) << \"Dropping unmatched input frame in stream \"\n+\t\t\t\t\t  << stream->name();\n+\t\t} else if (stream->isExternal() || b->metadata().timestamp == timestamp) {\n \t\t\t/* The calling function will pop the item from the queue. */\n \t\t\treturn b;\n \t\t} else {\ndiff --git a/src/libcamera/pipeline/raspberrypi/rpi_stream.h b/src/libcamera/pipeline/raspberrypi/rpi_stream.h\nindex ed4f4987..a6f573fa 100644\n--- a/src/libcamera/pipeline/raspberrypi/rpi_stream.h\n+++ b/src/libcamera/pipeline/raspberrypi/rpi_stream.h\n@@ -44,30 +44,20 @@ public:\n \n \tvoid setExternal(bool external)\n \t{\n+\t\t/* Import streams cannot be external. */\n+\t\tassert(!external || !importOnly_);\n \t\texternal_ = external;\n \t}\n \n \tbool isExternal() const\n \t{\n-\t\t/*\n-\t\t * Import streams cannot be external.\n-\t\t *\n-\t\t * RAW capture is a special case where we simply copy the RAW\n-\t\t * buffer out of the request. All other buffer handling happens\n-\t\t * as if the stream is internal.\n-\t\t */\n-\t\treturn external_ && !importOnly_;\n-\t}\n-\n-\tbool isImporter() const\n-\t{\n-\t\treturn importOnly_;\n+\t\treturn external_;\n \t}\n \n \tvoid reset()\n \t{\n \t\texternal_ = false;\n-\t\tinternalBuffers_.clear();\n+\t\tclearBuffers();\n \t}\n \n \tstd::string name() const\n@@ -77,67 +67,124 @@ public:\n \n \tvoid setExternalBuffers(std::vector<std::unique_ptr<FrameBuffer>> *buffers)\n \t{\n-\t\texternalBuffers_ = buffers;\n+\t\tstd::transform(buffers->begin(), buffers->end(), std::back_inserter(bufferList_),\n+\t\t\t       [](std::unique_ptr<FrameBuffer> &b) { return b.get(); });\n \t}\n \n-\tconst std::vector<std::unique_ptr<FrameBuffer>> *getBuffers() const\n+\tconst std::vector<FrameBuffer *> &getBuffers() const\n \t{\n-\t\treturn external_ ? externalBuffers_ : &internalBuffers_;\n+\t\treturn bufferList_;\n \t}\n \n \tvoid releaseBuffers()\n \t{\n \t\tdev_->releaseBuffers();\n-\t\tif (!external_ && !importOnly_)\n-\t\t\tinternalBuffers_.clear();\n+\t\tclearBuffers();\n \t}\n \n-\tint importBuffers(unsigned int count)\n+\tint prepareBuffers(unsigned int count)\n \t{\n+\t\tint ret;\n+\n+\t\tif (!importOnly_) {\n+\t\t\tif (count) {\n+\t\t\t\t/* Export some frame buffers for internal use. */\n+\t\t\t\tret = dev_->exportBuffers(count, &internalBuffers_);\n+\t\t\t\tif (ret < 0)\n+\t\t\t\t\treturn ret;\n+\n+\t\t\t\t/* Add these exported buffers to the internal/external buffer list. */\n+\t\t\t\tstd::transform(internalBuffers_.begin(), internalBuffers_.end(),\n+\t\t\t\t\t       std::back_inserter(bufferList_),\n+\t\t\t\t\t       [](std::unique_ptr<FrameBuffer> &b) { return b.get(); });\n+\n+\t\t\t\t/* Add these buffers to the queue of internal usable buffers. */\n+\t\t\t\tfor (auto const &buffer : internalBuffers_)\n+\t\t\t\t\tavailableBuffers_.push(buffer.get());\n+\t\t\t}\n+\n+\t\t\t/* We must import all internal/external exported buffers. */\n+\t\t\tcount = bufferList_.size();\n+\t\t}\n+\n \t\treturn dev_->importBuffers(count);\n \t}\n \n-\tint allocateBuffers(unsigned int count)\n+\tint queueAllBuffers()\n \t{\n-\t\treturn dev_->allocateBuffers(count, &internalBuffers_);\n-\t}\n+\t\tint ret;\n \n-\tint queueBuffers()\n-\t{\n \t\tif (external_)\n \t\t\treturn 0;\n \n-\t\tfor (auto &b : internalBuffers_) {\n-\t\t\tint ret = dev_->queueBuffer(b.get());\n-\t\t\tif (ret) {\n-\t\t\t\tLOG(RPISTREAM, Error) << \"Failed to queue buffers for \"\n-\t\t\t\t\t\t      << name_;\n+\t\twhile (!availableBuffers_.empty()) {\n+\t\t\tret = queueBuffer(availableBuffers_.front());\n+\t\t\tif (ret < 0)\n \t\t\t\treturn ret;\n-\t\t\t}\n+\n+\t\t\tavailableBuffers_.pop();\n \t\t}\n \n \t\treturn 0;\n \t}\n \n-\tbool findFrameBuffer(FrameBuffer *buffer) const\n+\tint queueBuffer(FrameBuffer *buffer)\n \t{\n-\t\tauto start = external_ ? externalBuffers_->begin() : internalBuffers_.begin();\n-\t\tauto end = external_ ? externalBuffers_->end() : internalBuffers_.end();\n+\t\t/*\n+\t\t * A nullptr buffer implies an external stream, but no external\n+\t\t * buffer has been supplied. So, pick one from the availableBuffers_\n+\t\t * queue.\n+\t\t */\n+\t\tif (!buffer) {\n+\t\t\tif (availableBuffers_.empty()) {\n+\t\t\t\tLOG(RPISTREAM, Warning) << \"No buffers available for \"\n+\t\t\t\t\t\t\t<< name_;\n+\t\t\t\treturn -EINVAL;\n+\t\t\t}\n \n+\t\t\tbuffer = availableBuffers_.front();\n+\t\t\tavailableBuffers_.pop();\n+\t\t}\n+\n+\t\tLOG(RPISTREAM, Debug) << \"Queuing buffer \" << buffer->cookie()\n+\t\t\t\t      << \" for \" << name_;\n+\n+\t\tint ret = dev_->queueBuffer(buffer);\n+\t\tif (ret) {\n+\t\t\tLOG(RPISTREAM, Error) << \"Failed to queue buffer for \"\n+\t\t\t\t\t      << name_;\n+\t\t}\n+\n+\t\treturn ret;\n+\t}\n+\n+\tvoid returnBuffer(FrameBuffer *buffer)\n+\t{\n+\t\tavailableBuffers_.push(buffer);\n+\t}\n+\n+\tbool findFrameBuffer(FrameBuffer *buffer) const\n+\t{\n \t\tif (importOnly_)\n \t\t\treturn false;\n \n-\t\tif (std::find_if(start, end,\n-\t\t\t\t [buffer](std::unique_ptr<FrameBuffer> const &ref) { return ref.get() == buffer; }) != end)\n+\t\tif (std::find(bufferList_.begin(), bufferList_.end(), buffer) != bufferList_.end())\n \t\t\treturn true;\n \n \t\treturn false;\n \t}\n \n private:\n+\tvoid clearBuffers()\n+\t{\n+\t\tavailableBuffers_ = std::queue<FrameBuffer *>{};\n+\t\tinternalBuffers_.clear();\n+\t\tbufferList_.clear();\n+\t}\n+\n \t/*\n \t * Indicates that this stream is active externally, i.e. the buffers\n-\t * are provided by the application.\n+\t * might be provided by (and returned to) the application.\n \t */\n \tbool external_;\n \t/* Indicates that this stream only imports buffers, e.g. ISP input. */\n@@ -146,10 +193,19 @@ private:\n \tstd::string name_;\n \t/* The actual device stream. */\n \tstd::unique_ptr<V4L2VideoDevice> dev_;\n-\t/* Internally allocated framebuffers associated with this device stream. */\n+\t/* All framebuffers associated with this device stream. */\n+\tstd::vector<FrameBuffer *> bufferList_;\n+\t/*\n+\t * List of frame buffer that we can use if none have been provided by\n+\t * the application for external streams. This is populated by the\n+\t * buffers exported internally.\n+\t */\n+\tstd::queue<FrameBuffer *> availableBuffers_;\n+\t/*\n+\t * This is a list of buffers exported internally. Need to keep this around\n+\t * as the stream needs to maintain ownership of these buffers.\n+\t */\n \tstd::vector<std::unique_ptr<FrameBuffer>> internalBuffers_;\n-\t/* Externally allocated framebuffers associated with this device stream. */\n-\tstd::vector<std::unique_ptr<FrameBuffer>> *externalBuffers_;\n };\n \n /*\n",
    "prefixes": [
        "libcamera-devel",
        "6/9"
    ]
}