pythoncachingffmpeghttp-live-streamingstreamlink

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?


Solution

  • 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