import subprocess
import time
import os

# File containing a list of video file paths, one per line
video_list_file = 'videos.txt'

# HLS output settings
hls_playlist = 'HLS/live.m3u8'
hls_segment_duration = 10 # in seconds

# Create an empty playlist
subprocess.run(['echo', '#EXTM3U', '>', hls_playlist], check=True)

while True:
    # Read the list of videos
    with open(video_list_file, 'r') as f:
        videos = [line.strip() for line in f]

    # Iterate through the list of videos and add them to the HLS playlist
    for video in videos:
        # Create the HLS segments for the video
        # subprocess.run(['ffmpeg', '-re', '-i', video, '-c', 'copy','-f', 'hls', '-hls_time', str(hls_segment_duration), '-hls_list_size','0', '-hls_flags', ' +append_list', '-hls_segment_filename', 'HLS/live_%03d.ts', '-hls_base_url', hls_playlist , hls_playlist], check=True)
        
        os.system("ffmpeg -re -i '"+video+"' -c copy -f hls -hls_time 10 -hls_list_size 0 -hls_flags +append_list -hls_segment_filename 'HLS/live-%03d.ts' -hls_base_url HLS/live.m3u8 HLS/live.m3u8")

        # ffmpeg -i Trapped.mp4 -c copy -f hls -hls_time 10 -hls_list_size 0 -hls_flags +append_list -hls_segment_filename 'playlist-%03d.ts' -hls_base_url live.m3u8
        # wait for the video to end
        # result = subprocess.run(['ffmpeg', '-i', video, '-f', 'null', '-'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
        # duration_search = re.search("Duration: (.*?),", result.stdout.decode())
        # if duration_search:
        #     duration = duration_search.group(1)
        #     duration_parts = duration.split(":")
        #     duration_seconds = int(duration_parts[0]) * 3600 + int(duration_parts[1]) * 60 + int(duration_parts[2])
        #     time.sleep(duration_seconds)
    # infinite loop


    