Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enable cache on ffmpeg to record streaming

now I'm using steamlink and ffmpeg to record streams and save them to a file, many times the video file saved have so much lag. I found this link https://www.reddit.com/r/Twitch/comments/62601b/laggy_stream_on_streamlinklivestreamer_but_not_on/ where they claim that the lag problem occurs from the fact of not having the cache enabled on the player. I tried putting options -hls_allow_cache allowcache -segment_list_flags cache with the result that the ffmpeg process starts for 8seconds more or less, after which it ends and starts again immediately afterwards without returning a video file,if I don't put those two options the video is recorded correctly but most of the time with some lag.

Obviously if I visit streaming from the browser I have no lag problem

this is the code

from streamlink import Streamlink, NoPluginError, PluginError
streamlink = Streamlink()
#this code is just a snippet, it is inside a while loop to restart the process
try:
    streams = streamlink.streams(m3u8_url)
    stream_url = streams['best'].url
    #note hls options not seem to work
    ffmpeg_process = Popen(
        ["ffmpeg", "-hide_banner", "-loglevel", "panic", "-y","-hls_allow_cache", "allowcache", "-segment_list_flags", "cache","-i", stream_url, "-fs", "10M", "-c", "copy",
        "-bsf:a", "aac_adtstoasc", fileName])

    ffmpeg_process.wait()

except NoPluginError:
    print("noplugin")

except PluginError:
    print("plugin")

except Exception as e:
    print(e)

what are the best options to enable the cache and limit the lag as much as possible?

like image 574
JayJona Avatar asked Mar 03 '23 17:03

JayJona


2 Answers

You can read FFmpeg StreamingGuide for more details on Latency. For instances, you have

an option -fflags nobuffer which might possibly help, usually for receiving streams ​reduce latency.

As you can read here about nobuffer

Reduce the latency introduced by buffering during initial input streams analysis.

like image 115
Tiago Martins Peres Avatar answered Mar 05 '23 16:03

Tiago Martins Peres


I simply solved the lag problem by avoiding using ffmpeg to save videos but using streamlink directly and writing a .mp4 file

streamlink = Streamlink()
try:
    streams = streamlink.streams(m3u8_url)
    stream_url = streams['480p']
    fd = stream_url.open()

    out = open(fileName,"wb")

    while True:
        data = fd.read(1024)
        if data is None or data == -1 or data == 0:
           break
        else:
            out.write(data)
      fd.flush()
      fd.close()
      out.flush()
      out.close()
except NoPluginError:
    #handle exception        
except PluginError:
    #handle exception        
except StreamError:
    #handle exception        
except Exception as e:
    #handle exception
like image 25
JayJona Avatar answered Mar 05 '23 15:03

JayJona