I am using picamera2 Python library on Raspberry Pi 3B+. My goal is to simultaneously record and stream video on the network. Since this library doesn't provide this simultaneous ability out of the box, I wrote the following code to achieve this:
def __startStream(self):
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as self.sock:
self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.sock.bind(("0.0.0.0", 5001))
self.sock.listen()
self.conn, addr = self.sock.accept()
net_stream = self.conn.makefile("wb")
rec_stream = open(f"rec.mp4", 'wb')
def write_both(data):
rec_stream.write(data)
return net_stream._write(data)
net_stream._write = net_stream.write
net_stream.write = write_both
self.picam2.encoder.output = FileOutput(net_stream)
self.picam2.start_encoder()
self.picam2.start()
The problem with this code is that I am resorting to using BufferedWriter to save data into that video file, which does not properly format it as a video file, therefore it can't be imported into any video editing application, and very few players can play it.
I want to replace that BufferedWriter with some other library that would properly format this video file. I tried OpenCV:
rec_stream = cv2.VideoWriter('video.avi', -1, 25, (1024, 600))
But it throws errors, as it doesn't like the data that picamera2 is providing, and I can't find any info on how to convert it to something that it would accept.
Can anyone please suggest how can I achieve writing this video data to properly formatted video file?