Crow multipart response

168 Views Asked by At

How can i create a video feed with c++ crow multipart response? Sending a single image (see "/img") works as expected. But the "/stream" also just sends one frame. I think the problem is that res.end() flushes the first frame, but also closes the connection.

i set up a minimal example of the working "/img" route and the faulty "/stream" route:

#include <opencv2/opencv.hpp>
#include <sstream>
#include <vector>
#include "crow.h"

void streamWebcam(crow::response& res) {
    cv::VideoCapture cap(0); // Open the default camera
    if (!cap.isOpened()) {
        res.code = 500; // Internal Server Error
        res.end();
        return;
    }

    res.set_header("Content-Type", "multipart/x-mixed-replace;boundary=frameboundary");
    res.write("--frameboundary\r\n");

    while (res.is_alive()) {
        cv::Mat frame;
        cap >> frame; // Capture a frame
        if (frame.empty()) {
            break;
        }

        std::vector<uchar> buffer;
        cv::imencode(".jpg", frame, buffer);
        std::string image_data(buffer.begin(), buffer.end());

        std::ostringstream ss;
        ss << "Content-Type: image/jpeg\r\n";
        ss << "Content-Length: " << buffer.size() << "\r\n\r\n";
        res.write(ss.str());
        res.write(image_data);
        res.write("\r\n--frameboundary\r\n");
        res.end(); // TODO HERE!
        std::this_thread::sleep_for(std::chrono::milliseconds(40));
    }
    res.end();
}

int main() {
    crow::SimpleApp app;
    cv::Mat image = cv::imread("/abs/path/to/img.jpg");

    CROW_ROUTE(app, "/img")
    ([image](){
        
        if (image.empty()) {
            return crow::response(404);
        }
        std::vector<uchar> buffer;
        cv::imencode(".jpg", image, buffer);
        std::string image_data(buffer.begin(), buffer.end());

        crow::response res;
        res.set_header("Content-Type", "image/jpeg");
        res.write(image_data);
        return res;
    });

    CROW_ROUTE(app, "/stream")
    ([](const crow::request&, crow::response& res) {
        streamWebcam(res);
    });

    app.port(8080).multithreaded().run();
}
0

There are 0 best solutions below