video-streaming-poc/transfer.h

72 lines
2.1 KiB
C++

#ifndef TRANSFER_H
#define TRANSFER_H
#include <opencv2/core/mat.hpp>
#include <opencv2/imgcodecs.hpp>
#include <sys/socket.h>
#include <iostream>
inline void serializeImage(const cv::Mat& image, std::vector<uchar>& buffer) {
cv::imencode(".jpg", image, buffer);
}
int sendImage(int socket, const cv::Mat& image, std::vector<uchar>& buffer) {
serializeImage(image, buffer);
size_t totalSent = 0;
// first send the size of the serialized image
const size_t size = buffer.size();
std::cout << "Buffer size: " << size << std::endl;
if (const ssize_t sent = send(socket, &size, sizeof(size), 0); sent == -1) {
perror("Error sending data");
return -1;
}
// then start sending the serialized image
while (totalSent < size) {
const ssize_t sent = send(socket, buffer.data() + totalSent, size - totalSent, 0);
if (sent == -1) {
perror("Error sending data");
return -1;
}
totalSent += sent;
std::cout << "Packet sent (" << sent << " bytes, total " << totalSent << " bytes)" << std::endl;
}
return 0;
}
int recvImage(int socket, std::vector<uchar>& buffer) {
size_t dataSize;
// first receive the size of the image
ssize_t sizeReceived = recv(socket, &dataSize, sizeof(size_t), 0);
if (sizeReceived <= 0) {
return -1;
}
std::cout << "Buffer size: " << dataSize << std::endl;
// resize the buffer to fit the whole image
buffer.resize(dataSize);
// start receiving the image until the whole thing arrives
size_t totalReceived = 0;
while (totalReceived < dataSize) {
ssize_t bytesReceived = recv(socket, buffer.data() + totalReceived, dataSize, 0);
if (bytesReceived <= 0) {
buffer.clear();
return -1;
}
totalReceived += bytesReceived;
std::cout << "Packet received (" << bytesReceived << " bytes, total " << totalReceived << " bytes)" << std::endl;
}
return 0;
}
bool applyImage(cv::Mat& image, std::vector<uchar> *src) {
// decode the image into an OpenCV Mat
cv::imdecode(*src, 0, &image);
return true;
}
#endif //TRANSFER_H