python – ffmpeg video streaming issue

I am trying to embed an adb video stream into an html site with flask, and the code I have keeps on returning this same error:

FFmpeg: [mjpeg @ 0x156631c10] Could not find codec parameters for stream 0 (Video: mjpeg, none(bt470bg/unknown/unknown)): unspecified size
FFmpeg: Consider increasing the value for the ‘analyzeduration’ (1000000) and ‘probesize’ (5000000) options
FFmpeg: Input #0, mjpeg, from ‘pipe:0’:
FFmpeg: Duration: N/A, bitrate: N/A
FFmpeg: Stream #0:0: Video: mjpeg, none(bt470bg/unknown/unknown), 25 fps, 1200k tbr, 1200k tbn
FFmpeg: Output #0, mpegts, to ‘pipe:1’:
FFmpeg: [out#0/mpegts @ 0x156632110] Output file does not contain any stream
FFmpeg: Error opening output file pipe:1.
FFmpeg: Error opening output files: Invalid argument

this is my code:


from flask import Flask, Response
import subprocess
import json
import threading

app = Flask(__name__)

with open("data_file.json", "r") as f:
    config_data = json.load(f)

user = config_data["Users"]["Test User 1"]


def log_ffmpeg_errors(proc):
    for line in iter(proc.stderr.readline, b''):
        if line:
            print("FFmpeg:", line.decode(), end='')


def connect_device(ip, port):
    try:
        # Reconnect if device is offline
        subprocess.run(["adb", "tcpip", str(port)])
        subprocess.run(["adb", "connect", ip])
        # Check if the device is online
        devices = subprocess.check_output(["adb", "devices"]).decode()
        if "offline" in devices:
            raise Exception("Device is offline")
    except Exception as e:
        print(f"Error connecting device: {e}")


def generate_video_stream():
    adb_cmd = ["adb", "exec-out", "screenrecord", "--output-format=mjpeg"]  # Use MJPEG output
    ffmpeg_cmd = [
        "ffmpeg",
        "-f", "mjpeg",
        "-analyzeduration", "1000000", 
        "-probesize", "5000000",  
        "-i", "pipe:0", 
        "-q:v", "5",
        "-r", "10",
        "-vcodec", "mjpeg",  
        "-s", "1280x720", 
        "-f", "mpegts", 
        "pipe:1" 
    ]

    adb_proc = subprocess.Popen(adb_cmd, stdout=subprocess.PIPE)
    ffmpeg_proc = subprocess.Popen(ffmpeg_cmd, stdin=adb_proc.stdout, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

    threading.Thread(target=log_ffmpeg_errors, args=(ffmpeg_proc,), daemon=True).start()

    try:
        while True:
            frame = ffmpeg_proc.stdout.read(4096)
            if not frame:
                break
            yield (b'--frame\r\n'
                   b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n')

    finally:
        adb_proc.terminate()
        ffmpeg_proc.terminate()

@app.route('/video_feed')
def video_feed():
    return Response(generate_video_stream(), mimetype="multipart/x-mixed-replace; boundary=frame")

if __name__ == "__main__":
    connect_device(user["IP"], user["port"])
    app.run(debug=True, host="0.0.0.0", port=8080)



Read more here: Source link