-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQuickVideoCutter.py
More file actions
402 lines (335 loc) · 14.1 KB
/
QuickVideoCutter.py
File metadata and controls
402 lines (335 loc) · 14.1 KB
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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
import os
import sys
import threading
import time
import traceback
from queue import Queue, Empty
from tkinter import filedialog, messagebox
import ttkbootstrap as tb
import tkinter as tk
from tkinterdnd2 import DND_FILES, TkinterDnD
import subprocess
# Windows-only flag
CREATE_NO_WINDOW = 0x08000000
# =================== CONFIG ===================
APP_NAME = "QuickVideoCutter – Video Cutter"
APP_VERSION = "1.0.0"
FFMPEG_PATH = r"C:\ffmpeg\bin\ffmpeg.exe"
FFPLAY_PATH = r"C:\ffmpeg\bin\ffplay.exe"
SUPPORTED_FORMATS = ["mp4", "mov", "avi", "mkv", "flv", "webm"]
# =================== APP ===================
app = TkinterDnD.Tk()
app.title(f"{APP_NAME} v{APP_VERSION}")
app.geometry("1150x740")
tb.Style("darkly")
# =================== STATE ===================
video_list = []
ui_queue = Queue()
stop_flag = False
pause_flag = False
preview_process = None
video_duration = tb.IntVar(value=0)
start_sec = tb.DoubleVar(value=0)
end_sec = tb.DoubleVar(value=0)
# =================== UTIL ===================
def log_error():
with open("error.log", "a", encoding="utf-8") as f:
f.write(traceback.format_exc() + "\n")
def ffmpeg_exists():
return os.path.isfile(FFMPEG_PATH)
def resource_path(file_name):
base_path = getattr(sys, "_MEIPASS", os.path.dirname(os.path.abspath(__file__)))
return os.path.join(base_path, file_name)
def hhmmss_to_seconds(value: str) -> float:
try:
parts = value.split(":")
parts = [float(p) for p in parts]
if len(parts) == 3:
h, m, s = parts
return h * 3600 + m * 60 + s
elif len(parts) == 2:
m, s = parts
return m * 60 + s
return parts[0]
except Exception:
return 0.0
def seconds_to_hhmmss(seconds: float) -> str:
seconds = max(0, int(seconds))
h = seconds // 3600
m = (seconds % 3600) // 60
s = seconds % 60
return f"{h:02}:{m:02}:{s:02}"
def get_video_duration(file_path):
try:
cmd = [FFMPEG_PATH, "-i", file_path, "-hide_banner"]
proc = subprocess.Popen(
cmd,
stderr=subprocess.PIPE,
stdout=subprocess.DEVNULL,
text=True,
creationflags=CREATE_NO_WINDOW
)
for line in proc.stderr:
if "Duration:" in line:
dur = line.split("Duration:")[1].split(",")[0].strip()
h, m, s = dur.split(":")
return int(float(h) * 3600 + float(m) * 60 + float(s))
except Exception:
log_error()
return 0
def load_duration_from_selection(event=None):
if not listbox.curselection():
return
video = listbox.get(listbox.curselection()[0])
duration = get_video_duration(video)
video_duration.set(duration)
start_sec.set(0)
end_sec.set(duration)
start_time_var.set(seconds_to_hhmmss(0))
end_time_var.set(seconds_to_hhmmss(duration))
start_scale.config(to=duration)
end_scale.config(to=duration)
def show_about():
messagebox.showinfo(
f"About {APP_NAME} v{APP_VERSION}",
f"{APP_NAME} v{APP_VERSION}\n"
"Batch video cutter / trimmer with live preview and FFmpeg processing.\n\n"
"Features:\n"
"• Drag & drop or browse video files\n"
"• Trim video by start/end times\n"
"• Batch processing\n"
"• Live preview (Play / Stop)\n"
"• Multiple export formats\n"
"• Output folder selection\n"
"• Pause / Stop processing\n"
"• Real-time progress & log\n\n"
"Powered by FFmpeg\n"
"Built with Python, Tkinter & ttkbootstrap\n"
"© 2026 Mate Technologies"
)
try:
app.iconbitmap(resource_path("logo.ico"))
except Exception:
pass
# =================== MENU ===================
menubar = tb.Menu(app)
help_menu = tb.Menu(menubar, tearoff=0)
help_menu.add_command(label="About", command=show_about)
menubar.add_cascade(label="Help", menu=help_menu)
app.config(menu=menubar)
# =================== HEADER ===================
tb.Label(app, text=APP_NAME, font=("Segoe UI", 22, "bold")).pack(pady=(12, 2))
tb.Label(
app,
text="Trim or cut video files • Batch processing",
foreground="#9ca3af"
).pack(pady=(0, 10))
# =================== CARD: FILES ===================
files_card = tb.Labelframe(app, text="🎬 Video Files", padding=12)
files_card.pack(fill="x", padx=12, pady=6)
list_frame = tb.Frame(files_card)
list_frame.pack(fill="x")
listbox = tk.Listbox(list_frame, height=4)
listbox.pack(side="left", fill="x", expand=True)
scroll = tk.Scrollbar(list_frame, command=listbox.yview)
scroll.pack(side="right", fill="y")
listbox.config(yscrollcommand=scroll.set)
listbox.bind("<<ListboxSelect>>", load_duration_from_selection)
def add_video():
files = filedialog.askopenfilenames(
filetypes=[("Video Files", "*.mp4 *.mov *.avi *.mkv *.flv *.webm")]
)
for f in files:
if f not in video_list:
video_list.append(f)
ui_queue.put(("add", f))
if listbox.size() > 0:
listbox.selection_clear(0, "end")
listbox.selection_set(0)
load_duration_from_selection()
def clear_video():
video_list.clear()
ui_queue.put(("clear", None))
tb.Button(files_card, text="➕ Add Files", command=add_video, bootstyle="success").pack(side="left", pady=(12,0))
tb.Button(files_card, text="🧹 Clear", command=clear_video, bootstyle="danger-outline").pack(side="left", padx=8, pady=(12,0))
# =================== CARD: SETTINGS ===================
settings = tb.Labelframe(
app,
text="✂ Trim & Output Settings",
padding=16,
bootstyle="primary"
)
settings.pack(fill="x", padx=14, pady=8)
start_time_var = tb.StringVar(value="00:00:00")
end_time_var = tb.StringVar(value="00:00:00")
output_format = tb.StringVar(value="mp4")
output_dir = tb.StringVar()
# =================== TIME INPUT ROW ===================
time_row = tb.Frame(settings)
time_row.pack(fill="x", pady=(0, 6))
tb.Label(time_row, text="Start", font=("Segoe UI", 10, "bold")).pack(side="left")
tb.Entry(time_row, textvariable=start_time_var, width=10, justify="center").pack(side="left", padx=(6, 16))
tb.Label(time_row, text="End", font=("Segoe UI", 10, "bold")).pack(side="left")
tb.Entry(time_row, textvariable=end_time_var, width=10, justify="center").pack(side="left", padx=(6, 0))
# =================== RANGE SLIDERS ===================
slider_frame = tb.Frame(settings)
slider_frame.pack(fill="x", pady=(6, 12))
tb.Label(slider_frame, text="Start → End Selection", font=("Segoe UI", 9), foreground="#6c757d").pack(anchor="w", pady=(0, 4))
def update_from_slider(*_):
start_sec.set(int(start_sec.get()))
end_sec.set(int(end_sec.get()))
if start_sec.get() > end_sec.get():
end_sec.set(start_sec.get())
start_time_var.set(seconds_to_hhmmss(start_sec.get()))
end_time_var.set(seconds_to_hhmmss(end_sec.get()))
start_scale = tb.Scale(slider_frame, from_=0, to=0, variable=start_sec, orient="horizontal", command=lambda e: update_from_slider())
start_scale.pack(fill="x", expand=True)
end_scale = tb.Scale(slider_frame, from_=0, to=0, variable=end_sec, orient="horizontal", command=lambda e: update_from_slider())
end_scale.pack(fill="x", expand=True, pady=(4, 0))
# =================== FORMAT + OUTPUT ===================
bottom_row = tb.Frame(settings)
bottom_row.pack(fill="x", pady=(8, 4))
tb.Label(bottom_row, text="Format", font=("Segoe UI", 10, "bold")).pack(side="left")
tb.Combobox(bottom_row, values=SUPPORTED_FORMATS, textvariable=output_format, width=8, state="readonly").pack(side="left", padx=(6, 20))
tb.Label(bottom_row, text="Output Folder", font=("Segoe UI", 10, "bold")).pack(side="left")
tb.Entry(bottom_row, textvariable=output_dir).pack(side="left", fill="x", expand=True, padx=(6,6))
tb.Button(bottom_row, text="Browse", bootstyle="secondary-outline", command=lambda: output_dir.set(filedialog.askdirectory())).pack(side="left")
# =================== CARD: PROGRESS ===================
progress_card = tb.Labelframe(app, text="📊 Progress", padding=12)
progress_card.pack(fill="x", padx=12)
progress_var = tb.IntVar()
tb.Progressbar(progress_card, variable=progress_var, maximum=100, length=700).pack(side="left", padx=10)
status_lbl = tb.Label(progress_card, text="Ready")
status_lbl.pack(side="left")
# =================== CARD: LOG ===================
log_card = tb.Labelframe(app, text="📝 Log", padding=12)
log_card.pack(fill="both", expand=True, padx=12, pady=6)
log_text = tk.Text(log_card, height=4)
log_text.pack(fill="both", expand=True)
log_text.config(state="disabled")
# =================== CORE ===================
def process_video():
global stop_flag, pause_flag
stop_flag = pause_flag = False
if not ffmpeg_exists():
messagebox.showerror("Error", "FFmpeg not found at configured path.")
return
if not video_list:
messagebox.showerror("Error", "No video files selected.")
return
try:
start_sec_val = hhmmss_to_seconds(start_time_var.get())
end_sec_val = hhmmss_to_seconds(end_time_var.get())
except Exception:
messagebox.showerror("Error", "Invalid start/end time format.")
return
if start_sec_val >= end_sec_val:
messagebox.showerror("Error", "Start time must be less than end time.")
return
out_dir = output_dir.get() or os.path.dirname(video_list[0])
total = len(video_list)
for idx, video in enumerate(video_list):
if stop_flag:
break
while pause_flag:
time.sleep(0.1)
base = os.path.splitext(os.path.basename(video))[0]
out_file = os.path.join(out_dir, f"{base}_trim.{output_format.get()}")
cmd = [FFMPEG_PATH, "-y", "-ss", str(start_sec_val), "-to", str(end_sec_val), "-i", video, out_file]
ui_queue.put(("log", f"▶ Processing: {video}"))
try:
process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, creationflags=CREATE_NO_WINDOW)
process.wait()
ui_queue.put(("log", f"✅ Done: {out_file}"))
percent = int((idx + 1) / total * 100)
ui_queue.put(("progress", percent))
except Exception:
log_error()
ui_queue.put(("log", f"❌ Failed: {video}"))
ui_queue.put(("complete", "All videos processed"))
# =================== UI QUEUE ===================
def process_ui():
try:
while True:
cmd, data = ui_queue.get_nowait()
if cmd == "add":
listbox.insert("end", data)
elif cmd == "clear":
listbox.delete(0, "end")
elif cmd == "progress":
progress_var.set(data)
elif cmd == "log":
log_text.config(state="normal")
log_text.insert("end", data + "\n")
log_text.see("end")
log_text.config(state="disabled")
elif cmd == "complete":
status_lbl.config(text=data)
progress_var.set(100)
except Empty:
pass
app.after(100, process_ui)
# =================== PREVIEW ===================
def play_preview():
global preview_process
if not os.path.isfile(FFPLAY_PATH):
messagebox.showerror("Error", "FFplay not found.")
return
selection = listbox.curselection()
if not selection:
if listbox.size() > 0:
listbox.selection_set(0)
selection = (0,)
else:
messagebox.showerror("Error", "No video files available.")
return
video = listbox.get(selection[0])
stop_preview()
start_sec_val = hhmmss_to_seconds(start_time_var.get())
end_sec_val = hhmmss_to_seconds(end_time_var.get())
cmd = [FFPLAY_PATH, "-autoexit", "-loglevel", "quiet", "-ss", str(start_sec_val)]
if end_sec_val > start_sec_val:
cmd += ["-t", str(end_sec_val - start_sec_val)]
cmd.append(video)
def run_preview():
global preview_process
try:
preview_process = subprocess.Popen(cmd, creationflags=CREATE_NO_WINDOW)
preview_process.wait()
except Exception:
log_error()
finally:
preview_process = None
status_lbl.config(text="⏹ Preview Stopped")
threading.Thread(target=run_preview, daemon=True).start()
status_lbl.config(text="▶ Preview Playing...")
def stop_preview():
global preview_process
if preview_process and preview_process.poll() is None:
preview_process.terminate()
preview_process = None
status_lbl.config(text="⏹ Preview Stopped")
# =================== CONTROLS ===================
control_bar = tb.Frame(app)
control_bar.pack(pady=8)
def start():
threading.Thread(target=process_video, daemon=True).start()
tb.Button(control_bar, text="🚀 Start", bootstyle="success", command=start).pack(side="left", padx=6)
tb.Button(control_bar, text="⏸ Pause", bootstyle="warning-outline",
command=lambda: setattr(sys.modules[__name__], "pause_flag", not pause_flag)).pack(side="left", padx=6)
tb.Button(control_bar, text="🛑 Stop", bootstyle="danger-outline",
command=lambda: setattr(sys.modules[__name__], "stop_flag", True)).pack(side="left", padx=6)
tb.Button(control_bar, text="▶ Play Preview", bootstyle="info", command=play_preview).pack(side="left", padx=6)
tb.Button(control_bar, text="⏹ Stop Preview", bootstyle="secondary-outline", command=stop_preview).pack(side="left", padx=6)
# =================== DRAG & DROP ===================
def drop(event):
files = app.tk.splitlist(event.data)
for f in files:
if os.path.isfile(f) and f not in video_list:
video_list.append(f)
ui_queue.put(("add", f))
app.drop_target_register(DND_FILES)
app.dnd_bind("<<Drop>>", drop)
# =================== START ===================
app.after(100, process_ui)
app.mainloop()