I'm experimenting with a live stream on YouTube where I can switch the source of it based on some external inputs. So for example, I have two webcams and by default the live stream shows the stream from webcam 1. Then based on some input, it needs to switch to broadcasting the stream from webcam 2. This is what I have so far but it disrupts the stream with the buffering loading circle before it switches to the second one instead of being like an instant switch.
This is the code I'm using to create the ffmpeg command which runs to stream to YouTube.
def create_ffmpeg_cmd(cam_uri):
return ['ffmpeg',
'-i', cam_uri,
'-c:v', 'libx264',
'-f', 'flv',
f"{YOUTUBE_STREAM_URI}/{YOUTUBE_STREAM_KEY}"
]
This is the code block which runs to switch streams when next_stream_uri
is updated.
def run(self, *args, **kwargs):
command = create_ffmpeg_cmd(DEFAULT_CAM_URI)
p = sp.Popen(command, stdin=sp.PIPE)
stream_uri = self.next_stream_uri
while True:
if self.next_stream_uri != stream_uri:
print(f"Changing stream from {stream_uri} to {self.next_stream_uri} ...")
stream_uri = self.next_stream_uri
cmd = create_ffmpeg_cmd(stream_uri)
new_p = sp.Popen(cmd, stdin=sp.PIPE)
time.sleep(1)
p.terminate()
p = new_p
I put in the time.sleep(1)
before terminating the first one to see if that works but I still see some buffering happening. Not sure if it's even possible to achieve a seamless switch but wanted to see if there are some better ways of doing it.