import subprocess

videos_to_add =[]

# File containing the list of videos to concatenate
video_list_file = 'videos.txt'
# HLS playlist file
playlist_file = 'playlist.m3u8'

def check_for_new_videos():
    video_list_file = 'videos.txt'

    with open(video_list_file, "r") as f:
        current_videos = f.readlines()
    # code that check the new videos by comparing the current list of videos with the previous one.
    # Example :
    new_videos = []
    for video in videos_to_add:
        if video not in current_videos:
            new_videos.append(video)
    return new_videos

# Start ffmpeg to concatenate the videos and create the HLS live feed
ffmpeg = subprocess.Popen(['ffmpeg', '-f', 'concat', '-safe', '0', '-i', video_list_file, '-c', 'copy', '-f', 'hls',
                           '-hls_time', '10', '-hls_list_size', '0', '-hls_flags', 'delete_segments', playlist_file],
                         stdout=subprocess.PIPE, stderr=subprocess.PIPE)

while ffmpeg.poll() is None:
    stdout, stderr = ffmpeg.communicate()

    # Check for new videos
    new_videos = check_for_new_videos()
    if new_videos:
        with open(video_list_file, "a") as f:
            for video in new_videos:
                f.write(video + '\n')
        # Restart ff
