0

我设法将视频帧流式传输到 RTMP 服务器,但我也想流式传输音频 - 因为我不能使用 rawvideo 格式,现在我不知道 ffmpeg 视频需要多少字节发送到ffmpeg 流。

如果有更简单的方法可以做到这一点,我会更喜欢它,我尽我最大的努力发表评论,以使代码易于理解。

WIDTH = 1152
HEIGHT = 720
RTMP = ""
#Returns frame of a video
def read_frame(process1, width, height):
    frame_size = width * height * 3 #<--- I don't know how many bytes should I ask for.
    in_bytes = process1.stdout.read(frame_size)
    if len(in_bytes) == 0:
        return []
    else:
        assert len(in_bytes) == frame_size
        frame = (
            np
            .frombuffer(in_bytes, np.uint8)
            .reshape([height, width, 3])
        )
    return frame


def getVideoOutput(in_filename):
    args = (
        ffmpeg
        .input(in_filename # Path to file
        ,loglevel="quiet"#Don't show ffmpegs logs
        )
        .output('pipe:', format='flv')#Outputs a pipe
        .compile()
    )
    return subprocess.Popen(args, stdout=subprocess.PIPE)

#Start stream
def startStream(width, height):
    args = (
        ffmpeg
        .input('pipe:', #Sats to ffmpeg that the input is a stream
        format='flv'#Format of the video
        ,r="30"#Sets average fps
        ,s='{}x{}'.format(width, height)#Set the width and height of the input
        ,loglevel="quiet" #Don't show ffmpegs logs 
        )
        .output(RTMP,vcodec="libx264",preset="ultrafast",acodec="aac",format="flv")
        .overwrite_output()
        .compile()
    )
    return subprocess.Popen(args, stdin=subprocess.PIPE)

#Writes frame to the stream
def write_frame(process2, frame):
    process2.stdin.write(
        frame
        .astype(np.uint8)
        .tobytes()
    )

#Gets frames from multiple videos
def getBytes():
    for video in os.listdir(".\\Videos"):#Loops through videos in the videos folder 
    #while True:
        #video = os.listdir(".\\Videos")[0]
        videoPath = os.path.join(pathlib.Path().absolute(),"Videos",video)
        pipe = getVideoOutput(videoPath) #Get a stream of bytes from the video
        while True:
            frame = read_frame(pipe,WIDTH,HEIGHT)#Get a frame
            if frame == []:#If the video ends Go to the next one
                break
            yield frame#return the frame


stream = startStream(WIDTH,HEIGHT)#Starts stream to server and outputs a subprocess
FrameGenerator = getBytes()#Start generator

while True:
    write_frame(stream,next(FrameGenerator))#infinite loop writes to the stream a frame
4

0 回答 0