Skip to content

Instantly share code, notes, and snippets.

@jd20
Last active Mar 16, 2018
Embed
What would you like to do?
Testing PyAV encoding
import argparse
import av
import logging
import time
def parse_options(preset, tune, crf, x264_params, x265_params):
opts = {}
if preset:
opts['preset'] = preset
if tune:
opts['tune'] = tune
if crf:
opts['crf'] = crf
if x264_params:
opts['x264-params'] = x264_params
if x265_params:
opts['x265-params'] = x265_params
print(opts)
return opts
def encode(frame):
try:
opacket = stream.encode(frame)
except Exception:
return False
if opacket is not None:
try:
output.mux(opacket)
except Exception:
print('mux failed: ' + str(opacket))
return True
logging.basicConfig(level=logging.INFO)
logging.getLogger('libav').setLevel(logging.INFO)
arg_parser = argparse.ArgumentParser()
arg_parser.add_argument('-r', '--rate', default='12')
arg_parser.add_argument('-f', '--format', default='yuv420p')
arg_parser.add_argument('--width', type=int, default=640)
arg_parser.add_argument('--height', type=int, default=480)
arg_parser.add_argument('-c', '--codec', default='libx264')
arg_parser.add_argument('--preset', default='medium')
arg_parser.add_argument('--tune', default='')
arg_parser.add_argument('--crf', default='23')
arg_parser.add_argument('--x264-params')
arg_parser.add_argument('--x265-params')
arg_parser.add_argument('input', nargs=1)
arg_parser.add_argument('output', nargs=1)
args = arg_parser.parse_args()
container = av.open(args.input[0])
video_st = container.streams.video[0]
print("Input Stream:", video_st)
output = av.open(args.output[0], 'w')
stream = output.add_stream(args.codec, args.rate)
stream.pix_fmt = args.format
stream.width = args.width
stream.height = args.height
stream.options = parse_options(args.preset, args.tune, args.crf, args.x264_params, args.x265_params)
print("Output Stream:", stream)
last_update = 0
n = 0
for frame in container.decode(video=0):
frame.pts = frame.index / (12.0 * float(video_st.time_base))
frame.time_base = video_st.time_base
encode(frame)
n += 1
now = time.time()
if last_update == 0 or now - last_update > 0.1:
print(f"Wrote {n} frames", end=' \r')
last_update = now
while True:
if not encode(None):
break
output.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment