import av
import av.datasets

av.logging.set_level(av.logging.VERBOSE)

input_ = av.open(av.datasets.curated("pexels/time-lapse-video-of-night-sky-857195.mp4"))
output = av.open("remuxed.mkv", "w")

# Make an output stream using the input as a template. This copies the stream
# setup from one to the other.
in_stream = input_.streams.video[0]
out_stream = output.add_stream_from_template(in_stream)

for packet in input_.demux(in_stream):
    print(packet)

    # We need to skip the empty "flushing" packet that `demux` generates at the
    # end. Don't test `packet.dts is None` here: a valid keyframe can legitimately
    # have no DTS (e.g. the leading reordered packets of a B-frame stream in MKV),
    # and skipping it would drop the keyframe and corrupt the output.
    if packet.size == 0:
        continue

    # We need to assign the packet to the new stream.
    packet.stream = out_stream

    output.mux(packet)

input_.close()
output.close()
