Debian Codegraph @

examples/basics/parse.py

raw
1 import os
2 import subprocess
3
4 import av
5 import av.datasets
6
7 # We want an H.264 stream in the Annex B byte-stream format.
8 # We haven't exposed bitstream filters yet, so we're gonna use the `ffmpeg` CLI.
9 h264_path = "night-sky.h264"
10 if not os.path.exists(h264_path):
11 subprocess.check_call(
12 [
13 "ffmpeg",
14 "-i",
15 av.datasets.curated("pexels/time-lapse-video-of-night-sky-857195.mp4"),
16 "-vcodec",
17 "copy",
18 "-an",
19 "-bsf:v",
20 "h264_mp4toannexb",
21 h264_path,
22 ]
23 )
24
25
26 fh = open(h264_path, "rb")
27
28 codec = av.CodecContext.create("h264", "r")
29
30 while True:
31 chunk = fh.read(1 << 16)
32
33 packets = codec.parse(chunk)
34 print("Parsed {} packets from {} bytes:".format(len(packets), len(chunk)))
35
36 for packet in packets:
37 print(" ", packet)
38
39 frames = codec.decode(packet)
40 for frame in frames:
41 print(" ", frame)
42
43 # We wait until the end to bail so that the last empty `buf` flushes
44 # the parser.
45 if not chunk:
46 break