Skip to content

Instantly share code, notes, and snippets.

@marcan
Created September 12, 2017 18:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save marcan/9e33fedbf1a5386378b7fa00cdcc0695 to your computer and use it in GitHub Desktop.
Save marcan/9e33fedbf1a5386378b7fa00cdcc0695 to your computer and use it in GitHub Desktop.
Two h.264 framerates for the price of one
#!/usr/bin/python3
import sys
KEYINT = 30
# Encode your input like this (example):
# x264 --crf 20 --keyint 30 --min-keyint 30 --bframes 1 --no-b-adapt <input> -o <output.h264>
# Produces display order IBPBPBP...BPBPP|IBPBPBP...BPBPP|...
# Decoding (file) order IPBPBPB...PBPBP|IPBPBPB...PBPBP|...
# Loads whole file into memory. Fine for PoC...
d = open(sys.argv[1], "rb").read()
out = open(sys.argv[2], "wb")
CODES = { 0x67: "+", 0x68: "I", 0x41: "P", 0x01: "B" }
ctr = 0
for nal in d.split(b"\x00\x00\x00\x01"):
if not nal:
continue
if nal[0] == 0x68: # Reset on I frame
ctr = 0
elif nal[0] in (0x41, 0x01):
ctr += 1
print("%2d: %02x [%s] (%d)" % (ctr, nal[0], CODES.get(nal[0],"?"), len(nal)))
if nal[0] == 0x01: # drop B frames
continue
if nal[0] == 0x41 and ctr == (KEYINT - 1): # drop the last P frame
continue
out.write(b"\x00\x00\x00\x01" + nal)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment