PyAV
PyAV copied to clipboard
Encoding issue at the beginning of videos when using libx264
The first few frames of an encoded video seem to have errors when using libx264. It does not seem to be the case when using mpeg4.

Example code
#!/usr/bin/env python3
import numpy
import av
import cv2
#--------------------------------------------------------------------
def bounce(p, r, s, mn, mx):
return (0 < s and (p + r + s) > mx) or (0 > s and mn > (p - r + s))
def createVideo():
# Video
w = 640
h = 480
fps = 30
brate = 100000
duration = 10
# Output file name
outfile = './ball.mp4'
# Ball speed
xs = 10
ys = 10
# Ball size
sz = 20
# Initial position
x = int(w / 2)
y = int(h / 2)
# Audio sample rate, 8000, 44100, 48000
asr = 48000
# Time base
time_base = asr
# Attempt to create a video writer
avf = av.open(file=outfile, format=None, mode="w", options={})
if not avf:
print("!! Failed to create video file : " + outfile)
return
# Add video stream
vstream = avf.add_stream("libx264", rate=fps)
# vstream = avf.add_stream("mpeg4", rate=fps)
vstream.pix_fmt = "yuv420p"
vstream.width = w
vstream.height = h
vstream.bit_rate = brate
vstream.bit_rate_tolerance = int(brate / 10)
vstream.time_base = "1/" + str(time_base)
# Add audio stream
astream = avf.add_stream("aac", rate=asr, layout='stereo')
astream.time_base = "1/" + str(time_base)
# Create a blank image
arr = numpy.zeros([h,w,3], dtype=numpy.uint8)
# Number of audio samples per interval
nsamples = int(asr / fps)
# Create silence
silence = numpy.zeros((2, nsamples), dtype='int16')
# Create bouncy sound
bouncymono = (30000 * numpy.sin(2 * numpy.pi * numpy.arange(nsamples) * 440 / asr)).astype(numpy.int16)
att = int(nsamples / 3)
for i in range(0, att):
bouncymono[i] = (i/att) * bouncymono[i]
bouncymono[nsamples - i - 1] = (i/att) * bouncymono[nsamples - i - 1]
# Stereo bouncy sound
bouncysound = numpy.array([bouncymono, bouncymono])
# Write frames to file
for i in range(0, duration * fps):
bounced = False
# Update X position
if bounce(x, sz, xs, 0, w):
bounced = True
xs = -xs
x += xs
# Update Y position
if bounce(y, sz, ys, 0, h):
bounced = True
ys = -ys
y += ys
# Draw the ball
cv2.rectangle(arr, (0, 0), (w, h), (0, 0, 0), -1)
cv2.circle(arr, (x, y), sz, (255, 0, 0, 0), -1)
# Write video frame
frame = av.VideoFrame.from_ndarray(arr, format='rgb24')
frame.pts = int(i * time_base / fps)
frame.time_base = '1/' + str(time_base)
for packet in vstream.encode(frame):
avf.mux(packet)
# Bouncy sound?
atrack = bouncysound if bounced else silence
# Write audio
aframe = av.AudioFrame.from_ndarray(atrack, 's16p')
aframe.pts = int(i * time_base / fps)
aframe.sample_rate = asr
aframe.time_base = '1/' + str(time_base)
for packet in astream.encode(aframe):
avf.mux(packet)
# Finalize
for packet in vstream.encode():
avf.mux(packet)
for packet in astream.encode():
avf.mux(packet)
# Close the file
avf.close()
avf = None
if __name__ == '__main__':
createVideo()
At first glance, vstream.time_base = "1/" + str(time_base) seems iffy. You're setting the video timebase to be the audio sample rate.
So perhaps one is respecting your bad pts and one is not.
Please reduce your example to the minimum viable demonstration; there is too much here for us to reasonably deal with.
You are correct, changing the timebase fixes the issue. Thanks for your help.