Jojo71
Jojo71

Reputation: 89

Python PyAV how to flush to disk regularly

I am using PyAV for encoding a video stream from a camera and saving it to disk. This works in general, but I have one problem left: the file on the disk stays at 0kb regardless of how long i record. Onyl when I close the output_stream it saves to disk. Since I want to do hour long streams, I need to flush the stream regularly to disk. Also if my program crashes the file needs to be valid.

Here is my code for the recorder class ,which I call with "test.mkv" as output file.

class Recorder:
    def __init__(self) -> None:
        recorder_instances.append(self)
        self.frame_count = 0

    def start(self, output_file, width, height, fps):
        self.output_container = av.open(output_file, mode="w")
        self.output_stream = self.output_container.add_stream("libvpx-vp9", rate=fps)
        self.output_stream.width = width
        self.output_stream.height = height
        self.output_stream.options = {
            # Add more options as needed
        }

    def recieved_frame(self, frame):
        for packet in self.output_stream.encode(frame):
            self.output_container.mux(packet)
      
    def stop(self):
        # Flush any remaining packets
        for packet in self.output_stream.encode(None):
            self.output_container.mux(packet)
        # Close the output container
        self.output_container.close()

I already tried to use:

# Flush any remaining packets
for packet in self.output_stream.encode(None):
  self.output_container.mux(packet)

...inside the recieved_frame method, but that gives me an error: "end of file" when recieving the next package.

Upvotes: 1

Views: 196

Answers (1)

Christoph Rackwitz
Christoph Rackwitz

Reputation: 15516

Your file on disk isn't 0 bytes.

That's just Windows Explorer lagging in its display of the file's size.

Press F5 to make it update its display of the file's size.

Upvotes: 0

Related Questions