-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconcurrent_ffmpeg.py
102 lines (81 loc) · 2.98 KB
/
concurrent_ffmpeg.py
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
import subprocess
import os
from concurrent.futures import ThreadPoolExecutor
from pymediainfo import MediaInfo
def run_command(command):
command.insert(1, '-nostdin')
print(f"Running command: {' '.join(command)}") # Print the command
process = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
if process.stdout:
print(f"STDOUT: {process.stdout}")
if process.stderr:
print(f"STDERR: {process.stderr}")
def get_video_duration(input_file):
media_info = MediaInfo.parse(input_file)
for track in media_info.tracks:
if track.track_type == 'Video':
return float(track.duration) / 1000 # Convert from milliseconds to seconds
return None
def split_video(input_file, segment_time, output_folder):
command = [
'ffmpeg',
'-i', input_file,
'-c', 'copy',
'-map', '0',
'-segment_time', str(segment_time),
'-f', 'segment',
f'{output_folder}/segment_%03d.mp4'
]
run_command(command)
def apply_single_filter(input_path, output_path):
command = [
'ffmpeg',
'-i', input_path,
'-vf', 'scale=iw/2:-1', '-y',
output_path
]
run_command(command)
def apply_filter_concurrent(input_folder, output_folder):
with ThreadPoolExecutor() as executor:
futures = []
for segment in os.listdir(input_folder):
input_path = os.path.join(input_folder, segment)
output_path = os.path.join(output_folder, segment)
futures.append(executor.submit(apply_single_filter, input_path, output_path))
for future in futures:
future.result()
def concatenate_videos(input_folder, output_file):
with open("concat_list.txt", "w") as f:
for segment in sorted(os.listdir(input_folder)):
f.write(f"file '{os.path.join(input_folder, segment)}'\n")
command = [
'ffmpeg',
'-f', 'concat',
'-safe', '0',
'-i', 'concat_list.txt',
'-c', 'copy', '-y',
output_file
]
run_command(command)
def main():
input_file = 'input.mp4'
total_duration = get_video_duration(input_file)
if total_duration is None:
print("Could not fetch video duration.")
return
num_pieces = 3 # Number of pieces to split the video into
segment_time = total_duration / num_pieces
temp_folder = 'temp_segments'
filtered_folder = 'filtered_segments'
output_file = 'output.mp4'
os.makedirs(temp_folder, exist_ok=True)
os.makedirs(filtered_folder, exist_ok=True)
print(f'Splitting video into {num_pieces} pieces...')
split_video(input_file, segment_time, temp_folder)
print('Applying video filter concurrently...')
apply_filter_concurrent(temp_folder, filtered_folder)
print('Concatenating segments...')
concatenate_videos(filtered_folder, output_file)
print('Done!')
if __name__ == '__main__':
main()