Spaces:
Paused
Paused
import os | |
import logging | |
import uuid | |
from ffmpy import FFmpeg | |
# Set up logging | |
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s') | |
def ffmpeg_stream(file_url, token, output_dir="tmp/cache/stream"): | |
# Generate a unique directory for the stream | |
unique_id = str(uuid.uuid4()) | |
stream_dir = os.path.join(output_dir, unique_id) | |
if not os.path.exists(stream_dir): | |
os.makedirs(stream_dir) | |
# Set the output paths | |
output_path = os.path.join(stream_dir, 'output.m3u8') | |
segment_filename = os.path.join(stream_dir, 'segment_%03d.ts') | |
file_url = "'"+file_url+"'" | |
# Construct the FFmpeg command using ffmpy | |
ff = FFmpeg( | |
inputs={file_url: None}, | |
outputs={ | |
output_path: f'-c:v libx264 -crf 23 -preset medium -c:a aac -b:a 192k -f hls ' | |
f'-hls_time 10 -hls_list_size 0 -hls_segment_filename {segment_filename}' | |
}, | |
global_options=f'-headers \"Authorization: Bearer {token}\r\n"' | |
) | |
try: | |
# Log the command being executed | |
logging.debug(f"Running FFmpeg command: {ff.cmd}") | |
# Run the FFmpeg command | |
ff.run() | |
# Check if the output file was created | |
if os.path.exists(output_path): | |
logging.info(f"HLS playlist created at {output_path}") | |
else: | |
logging.error(f"HLS playlist not created at {output_path}") | |
return unique_id, output_path | |
except Exception as e: | |
logging.error(f"Error using FFmpeg to stream file: {e}") | |
return None, None | |
# Uncomment and modify the following lines if you want to test the script | |
if __name__ == "__main__": | |
url = "https://huggingface.co/Unicone-Studio/jellyfin_media/resolve/main/films/Funky%20Monkey%202004/Funky%20Monkey%20(2004)%20Web-dl%201080p.mp4" | |
token = os.getenv("TOKEN") | |
stream_id, output_path = ffmpeg_stream(url, token) | |
if stream_id: | |
logging.info(f"HLS playlist created with stream ID: {stream_id}") | |
else: | |
logging.error("Failed to create HLS playlist.") | |