File size: 2,319 Bytes
0bbba4e
f505705
 
 
 
 
 
 
 
 
0bbba4e
f505705
 
 
 
 
0bbba4e
 
f505705
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5c6ae28
 
f505705
 
5c6ae28
f505705
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bb9c4a8
5c6ae28
 
f505705
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
from ffmpy import FFmpeg
import os
import subprocess
import logging
import uuid

# 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"):
    stream_dir = output_dir

    if not os.path.exists(stream_dir):
        os.makedirs(stream_dir)

    # Set up the FFmpeg command for HLS
    output_path = stream_dir+'/output.m3u8'
    segment_filename = stream_dir+'/segment_%03d.ts'
    
    ffmpeg_command = [
        'ffmpeg',
        '-headers', f'Authorization: Bearer {token}',
        '-i', file_url,
        '-c:v', 'libx264',
        '-crf', '23',
        '-preset', 'medium',
        '-c:a', 'aac',
        '-b:a', '192k',
        '-f', 'hls',
        '-hls_time', '10',
        '-hls_list_size', '0',
        '-hls_segment_filename', segment_filename,
        output_path
    ]

    try:
        # Log the command being executed
        logging.debug(f"Running FFmpeg command: {' '.join(ffmpeg_command)}")
        
        # Run the FFmpeg command
        process = subprocess.Popen(
            ffmpeg_command,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE
        )

        # Capture stdout and stderr
        stdout, stderr = process.communicate()

        # Log FFmpeg output
        logging.debug("FFmpeg stdout: %s", stdout.decode())
        logging.error("FFmpeg stderr: %s", stderr.decode())

        # 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 the unique stream ID and process
        return process

    except Exception as e:
        logging.error(f"Error using FFmpeg to stream file: {e}")
        return None, None

# 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, process = 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.")