File size: 1,711 Bytes
06ee5b8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 requests
import subprocess
from urllib.parse import urlparse
import math

def download_file(url, local_filename):
    with requests.get(url, stream=True) as r:
        r.raise_for_status()
        with open(local_filename, 'wb') as f:
            for chunk in r.iter_content(chunk_size=8192): 
                f.write(chunk)
    return local_filename

def calculate_aspect_ratio(width, height):
    try:
        gcd = math.gcd(width, height)
        return f'{width//gcd}:{height//gcd}'
    except ZeroDivisionError:
        return "1:1"

def convert_video(input_file, output_file, width, height):
    aspect_ratio = calculate_aspect_ratio(width, height)
    ffmpeg_command = f'ffmpeg -i {input_file} -vf scale={width}:{height},setsar={aspect_ratio} -y -f hls {output_file}'
    
    try:
        process = subprocess.run(ffmpeg_command, shell=True, timeout=600, capture_output=True, text=True)
    except subprocess.TimeoutExpired:
        return "ffmpeg command timed out."
    except FileNotFoundError:
        return "ffmpeg is not installed."
    except Exception as e:
        return f"An error occurred: {str(e)}"
    
    if process.returncode != 0:
        return f"ffmpeg command failed with output: {process.stderr}"
    
    return "Video conversion completed successfully."

def main():
    url = 'http://techslides.com/demos/sample-videos/small.mp4'
    local_file = os.path.join('/tmp', os.path.basename(urlparse(url).path))
    download_file(url, local_file)
    
    width = 480
    height = 720
    output_file = '/tmp/output.m3u8'
    convert_result = convert_video(local_file, output_file, width, height)
    
    print(convert_result)

if __name__ == "__main__":
    main()