File size: 1,881 Bytes
f505705
24381da
7f9534f
f505705
 
 
 
7f9534f
fc60743
feb5ce7
fc60743
f505705
 
 
fc60743
 
 
7f9534f
 
 
 
 
5c6ae28
 
f505705
7f9534f
 
 
 
 
 
 
 
 
 
 
 
 
d451d18
24381da
f505705
 
 
d451d18
f505705
 
d451d18
7f9534f
 
 
 
 
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
import os
import logging
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", stream_id=None):
    # Generate a unique directory for the stream
    stream_dir = os.path.join(output_dir, stream_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')

    # Log the URL and output paths
    logging.debug(f"URL: {file_url}")
    logging.debug(f"Output Path: {output_path}")
    logging.debug(f"Segment Filename: {segment_filename}")

    try:
        # Log the command being executed
        logging.debug(f"Starting FFmpeg process with URL: {file_url}")

        # Run the FFmpeg command using ffmpeg-python
        process = (
            ffmpeg
            .input(file_url, headers=f"Authorization: Bearer {token}")
            .output(output_path, 
                    vcodec='libx264', crf=23, preset='medium', 
                    acodec='aac', audio_bitrate='192k', format='hls', 
                    hls_time=10, hls_list_size=0, 
                    hls_segment_filename=segment_filename)
        )

        process.run(capture_stdout=True, capture_stderr=True)

        # Check if the output file was created
        if os.path.exists(output_path):
            logging.info(f"HLS playlist created at {output_path}")
            return output_path
        else:
            logging.error(f"HLS playlist not created at {output_path}")
            return None

    except ffmpeg.Error as e:
        error_message = e.stderr.decode('utf8') if e.stderr else str(e)
        logging.error(f"Error using FFmpeg to stream file: {error_message}")
        return None