Skip to content
TheChatArchiveThe Chat Archive
o3-mini· OpenAIHugging Face LMArena Human Preference 140K

write a python script that will take the m3u8 link from clipboard, play the stream…

From a Chatbot Arena battleThe same person sent this prompt to two anonymous models at once. Compare it with Metallama-4-maverick-17b-128e-instruct’s answer.
  1. User

    write a python script that will take the m3u8 link from clipboard, play the stream ffmpeg in best quality, record the stream and saving each second, and also saving each frame with unique name. available for both live stream m3u8 and offline m3u8 videos.

  2. Assistant

    Below is one example of a Python script that reads an m3u8 URL from the clipboard and then launches three concurrent FFmpeg‐based processes:

    1. Plays the stream in a window using ffplay.
    2. Records the incoming stream into 1‑second segments (without re‑encoding, so you get “best quality” as supplied by the source).
    3. Extracts every frame as a JPEG file under the frames folder with a unique filename.

    Both live streams and “offline” (on‑disk) m3u8 videos should work as long as FFmpeg can read them.

    Note:
    • This script uses the Python package pyperclip so be sure to install it (e.g. via pip install pyperclip).
    • You must have ffmpeg and ffplay installed and available in your system’s PATH.
    • Running three processes simultaneously means FFmpeg will open three independent connections to the m3u8 URL. In most cases this is acceptable, but if you run into network or source issues you might consider more advanced piping/multiplexing.

    Save the script as, for example, stream_capture.py and run it with Python.


    #!/usr/bin/env python3
    """
    Stream Capture Script
    
    This script does the following:
     - Reads an m3u8 URL from the clipboard.
     - Launches ffplay to display the stream.
     - Uses ffmpeg to record the stream into 1-second segments.
     - Uses ffmpeg to extract/save each frame as a JPEG image.
    """
    
    import os
    import sys
    import subprocess
    import pyperclip
    import signal
    
    def create_frames_folder(folder="frames"):
        """Create a directory for the frame images if it does not exist."""
        if not os.path.exists(folder):
            os.makedirs(folder)
    
    def main():
        # Get m3u8 URL from the clipboard
        m3u8_link = pyperclip.paste().strip()
        if not m3u8_link.startswith("http"):
            print("Error: The clipboard does not seem to contain a valid m3u8 URL.")
            sys.exit(1)
            
        print(f"Using m3u8 link: {m3u8_link}")
        
        # Make sure the frames folder exists
        frames_folder = "frames"
        create_frames_folder(frames_folder)
        
        # Define the command to play the stream using ffplay.
        # You can adjust ffplay parameters (such as -fs for fullscreen) if desired.
        ffplay_cmd = [
            "ffplay",
            "-i", m3u8_link
            # Add more options here if you like, e.g., "-fs" for fullscreen:
            # "-fs"
        ]
        
        # Define the command to record the stream into 1-second segments.
        # Using '-c copy' preserves the original quality without re-encoding.
        # Files will be named: recorded_000.ts, recorded_001.ts, ...
        record_cmd = [
            "ffmpeg",
            "-i", m3u8_link,
            "-c", "copy",
            "-f", "segment",
            "-segment_time", "1",
            "-reset_timestamps", "1",
            "recorded_%03d.ts"
        ]
        
        # Define the command to extract each frame as a JPEG image.
        # Files will be saved under the frames folder as frame_000001.jpg, frame_000002.jpg, ...
        frame_cmd = [
            "ffmpeg",
            "-i", m3u8_link,
            "-qscale:v", "2",  # lower value = higher quality (2 is usually very good)
            os.path.join(frames_folder, "frame_%06d.jpg")
        ]
        
        # Start the three FFmpeg-related processes
        print("Launching ffplay to display the stream...")
        play_proc = subprocess.Popen(ffplay_cmd)
        
        print("Launching ffmpeg for 1-second segmented recording...")
        record_proc = subprocess.Popen(record_cmd)
        
        print("Launching ffmpeg for extracting frames...")
        frame_proc = subprocess.Popen(frame_cmd)
        
        # Define a signal handler to terminate all child processes gracefully (e.g., on Ctrl+C)
        def signal_handler(sig, frame):
            print("\nTermination signal received, shutting down processes...")
            for proc in (play_proc, record_proc, frame_proc):
                proc.send_signal(signal.SIGINT)  # send interruption signal
            # Wait a moment for processes to exit
            for proc in (play_proc, record_proc, frame_proc):
                proc.wait()
            sys.exit(0)
        
        signal.signal(signal.SIGINT, signal_handler)
        
        # Wait for the ffplay process to finish.
        # The recording and frame extraction processes will keep running as long as ffplay is active.
        try:
            play_proc.wait()
        except KeyboardInterrupt:
            # If Ctrl+C is pressed, our signal handler will take care of cleanup.
            pass
        
        # Optionally, once ffplay terminates, you may also decide to terminate the other processes.
        for proc in (record_proc, frame_proc):
            proc.terminate()
        print("All processes terminated.")
    
    if __name__ == "__main__":
        main()
    

    Explanation

    • Clipboard Reading:
      The script uses pyperclip.paste() to grab whatever text is in your clipboard and checks that it begins with "http". If it does not, it warns you and exits.

    • Directory Setup:
      A directory named frames is created (if it doesn't already exist) to store the JPEG images.

    • Launching Processes:
      Three subprocesses are started:

      1. ffplay Process: Displays the video stream.
      2. Recording Process: Uses FFmpeg with the segment muxer (-f segment) to save 1‑second chunks. The option -c copy is used so that no re‑encoding occurs.
      3. Frame Extraction Process: Uses FFmpeg to extract frames from the stream and save them into the frames folder. The -qscale:v 2 option tells FFmpeg to produce high‑quality JPEG images.
    • Signal Handling:
      If you press Ctrl+C (or otherwise signal termination), the script will try to cleanly shut down all three processes.

    Feel free to adjust FFmpeg parameters as needed, for example to change the output quality or filenames. Enjoy!

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.