-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathvideoeditor.py
More file actions
3397 lines (2812 loc) · 151 KB
/
Copy pathvideoeditor.py
File metadata and controls
3397 lines (2812 loc) · 151 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
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import onnxruntime
import sys
import os
import uuid
import subprocess
import re
import json
import ffmpeg
import copy
import tempfile
from plugins import PluginManager, ManagePluginsDialog
from PyQt6.QtWidgets import (QApplication, QMainWindow, QWidget, QVBoxLayout,
QHBoxLayout, QPushButton, QFileDialog, QLabel,
QScrollArea, QFrame, QProgressBar, QDialog,
QCheckBox, QDialogButtonBox, QMenu, QSplitter, QDockWidget,
QListWidget, QListWidgetItem, QMessageBox, QComboBox,
QFormLayout, QGroupBox, QLineEdit, QSlider)
from PyQt6.QtGui import (QPainter, QColor, QPen, QFont, QFontMetrics, QMouseEvent, QAction,
QPixmap, QImage, QDrag, QCursor, QKeyEvent, QIcon, QTransform)
from PyQt6.QtCore import (Qt, QPoint, QRect, QRectF, QSize, QPointF, QObject, QThread,
pyqtSignal, QTimer, QByteArray, QMimeData, QEvent)
from undo import UndoStack, TimelineStateChangeCommand, MoveClipsCommand
from playback import PlaybackManager
from encoding import Encoder
CONTAINER_PRESETS = {
'mp4': {
'vcodec': 'libx264', 'acodec': 'aac',
'allowed_vcodecs': ['libx264', 'libx265', 'mpeg4'],
'allowed_acodecs': ['aac', 'libmp3lame'],
'v_bitrate': '5M', 'a_bitrate': '192k'
},
'matroska': {
'vcodec': 'libx264', 'acodec': 'aac',
'allowed_vcodecs': ['libx264', 'libx265', 'libvpx-vp9'],
'allowed_acodecs': ['aac', 'libopus', 'libvorbis', 'flac'],
'v_bitrate': '5M', 'a_bitrate': '192k'
},
'mov': {
'vcodec': 'libx264', 'acodec': 'aac',
'allowed_vcodecs': ['libx264', 'prores_ks', 'mpeg4'],
'allowed_acodecs': ['aac', 'pcm_s16le'],
'v_bitrate': '8M', 'a_bitrate': '256k'
},
'avi': {
'vcodec': 'mpeg4', 'acodec': 'libmp3lame',
'allowed_vcodecs': ['mpeg4', 'msmpeg4'],
'allowed_acodecs': ['libmp3lame'],
'v_bitrate': '5M', 'a_bitrate': '192k'
},
'webm': {
'vcodec': 'libvpx-vp9', 'acodec': 'libopus',
'allowed_vcodecs': ['libvpx-vp9'],
'allowed_acodecs': ['libopus', 'libvorbis'],
'v_bitrate': '4M', 'a_bitrate': '192k'
},
'wav': {
'vcodec': None, 'acodec': 'pcm_s16le',
'allowed_vcodecs': [], 'allowed_acodecs': ['pcm_s16le', 'pcm_s24le'],
'v_bitrate': None, 'a_bitrate': None
},
'mp3': {
'vcodec': None, 'acodec': 'libmp3lame',
'allowed_vcodecs': [], 'allowed_acodecs': ['libmp3lame'],
'v_bitrate': None, 'a_bitrate': '192k'
},
'flac': {
'vcodec': None, 'acodec': 'flac',
'allowed_vcodecs': [], 'allowed_acodecs': ['flac'],
'v_bitrate': None, 'a_bitrate': None
},
'gif': {
'vcodec': 'gif', 'acodec': None,
'allowed_vcodecs': ['gif'], 'allowed_acodecs': [],
'v_bitrate': None, 'a_bitrate': None
},
'oga': { # Using oga for ogg audio
'vcodec': None, 'acodec': 'libvorbis',
'allowed_vcodecs': [], 'allowed_acodecs': ['libvorbis', 'libopus'],
'v_bitrate': None, 'a_bitrate': '192k'
}
}
_cached_formats = None
_cached_video_codecs = None
_cached_audio_codecs = None
def download_ffmpeg():
if os.name != 'nt': return
exes = ['ffmpeg.exe', 'ffprobe.exe', 'ffplay.exe']
if all(os.path.exists(e) for e in exes): return
api_url = 'https://api.github.com/repos/GyanD/codexffmpeg/releases/latest'
import requests
r = requests.get(api_url, headers={'Accept': 'application/vnd.github+json'})
assets = r.json().get('assets', [])
zip_asset = next((a for a in assets if 'essentials_build.zip' in a['name']), None)
if not zip_asset: return
zip_url = zip_asset['browser_download_url']
zip_name = zip_asset['name']
from tqdm import tqdm
with requests.get(zip_url, stream=True) as resp:
total = int(resp.headers.get('Content-Length', 0))
with open(zip_name, 'wb') as f, tqdm(total=total, unit='B', unit_scale=True) as pbar:
for chunk in resp.iter_content(chunk_size=8192):
f.write(chunk)
pbar.update(len(chunk))
import zipfile
with zipfile.ZipFile(zip_name) as z:
for f in z.namelist():
if f.endswith(tuple(exes)) and '/bin/' in f:
z.extract(f)
os.rename(f, os.path.basename(f))
os.remove(zip_name)
def run_ffmpeg_command(args):
try:
startupinfo = None
if hasattr(subprocess, 'STARTUPINFO'):
startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
startupinfo.wShowWindow = subprocess.SW_HIDE
result = subprocess.run(
['ffmpeg'] + args,
capture_output=True, text=True, encoding='utf-8',
errors='ignore', startupinfo=startupinfo
)
if result.returncode != 0 and "Unrecognized option" not in result.stderr:
print(f"FFmpeg command failed: {' '.join(args)}\n{result.stderr}")
return ""
return result.stdout
except FileNotFoundError:
print("Error: ffmpeg not found. Please ensure it is in your system's PATH.")
return None
except Exception as e:
print(f"An error occurred while running ffmpeg: {e}")
return None
def get_available_formats():
global _cached_formats
if _cached_formats is not None:
return _cached_formats
output = run_ffmpeg_command(['-formats'])
if not output:
_cached_formats = {}
return {}
formats = {}
lines = output.split('\n')
header_found = False
for line in lines:
if "---" in line:
header_found = True
continue
if not header_found or not line.strip():
continue
if line[2] == 'E':
parts = line[4:].strip().split(None, 1)
if len(parts) == 2:
names, description = parts
primary_name = names.split(',')[0].strip()
formats[primary_name] = description.strip()
_cached_formats = dict(sorted(formats.items()))
return _cached_formats
def get_available_codecs(codec_type='video'):
global _cached_video_codecs, _cached_audio_codecs
if codec_type == 'video' and _cached_video_codecs is not None: return _cached_video_codecs
if codec_type == 'audio' and _cached_audio_codecs is not None: return _cached_audio_codecs
output = run_ffmpeg_command(['-encoders'])
if not output:
if codec_type == 'video': _cached_video_codecs = {}
else: _cached_audio_codecs = {}
return {}
video_codecs = {}
audio_codecs = {}
lines = output.split('\n')
header_found = False
for line in lines:
if "------" in line:
header_found = True
continue
if not header_found or not line.strip():
continue
parts = line.strip().split(None, 2)
if len(parts) < 3:
continue
flags, name, description = parts
type_flag = flags[0]
clean_description = re.sub(r'\s*\(codec .*\)$', '', description).strip()
if type_flag == 'V':
video_codecs[name] = clean_description
elif type_flag == 'A':
audio_codecs[name] = clean_description
_cached_video_codecs = dict(sorted(video_codecs.items()))
_cached_audio_codecs = dict(sorted(audio_codecs.items()))
return _cached_video_codecs if codec_type == 'video' else _cached_audio_codecs
def _get_subtitle_duration_ms(file_path):
last_time_ms = 0
try:
with open(file_path, 'r', encoding='utf-8', errors='ignore') as f:
content = f.read()
# SRT format: 00:00:20,123 --> 00:00:22,456
srt_matches = re.findall(r'\d{2}:\d{2}:\d{2},\d{3}\s+-->\s+(\d{2}):(\d{2}):(\d{2}),(\d{3})', content)
if srt_matches:
for h, m, s, ms in srt_matches:
time_ms = int(h) * 3600000 + int(m) * 60000 + int(s) * 1000 + int(ms)
if time_ms > last_time_ms:
last_time_ms = time_ms
return last_time_ms
# ASS format: Dialogue: 0,0:00:07.84,0:00:10.25,...
ass_matches = re.findall(r'Dialogue:.+?,(\d):(\d{2}):(\d{2})\.(\d{2}),(\d):(\d{2}):(\d{2})\.(\d{2})', content)
if ass_matches:
for _, _, _, _, h, m, s, cs in ass_matches:
time_ms = int(h) * 3600000 + int(m) * 60000 + int(s) * 1000 + int(cs) * 10
if time_ms > last_time_ms:
last_time_ms = time_ms
return last_time_ms
except Exception as e:
print(f"Could not parse subtitle duration for {os.path.basename(file_path)}: {e}")
return 5000 # Fallback to 5 seconds if parsing fails or file is empty
def _parse_timecode_string_to_ms(tc_string):
if not isinstance(tc_string, str):
return 0
parts = tc_string.split(':')
try:
if len(parts) == 3:
h = int(parts[0])
m = int(parts[1])
s_parts = parts[2].split('.')
s = int(s_parts[0])
ms = 0
if len(s_parts) > 1:
ms_str = s_parts[1]
ms = int((ms_str + '000')[:3])
return (h * 3600 + m * 60 + s) * 1000 + ms
except (ValueError, IndexError):
return 0
return 0
class TimelineClip:
def __init__(self, source_path, timeline_start_ms, clip_start_ms, duration_ms, track_index, track_type, media_type, group_id):
self.id = str(uuid.uuid4())
self.source_path = source_path
self.timeline_start_ms = int(timeline_start_ms)
self.clip_start_ms = int(clip_start_ms)
self.duration_ms = int(duration_ms)
self.track_index = track_index
self.track_type = track_type
self.media_type = media_type
self.group_id = group_id
@property
def timeline_end_ms(self):
return self.timeline_start_ms + self.duration_ms
class Timeline:
def __init__(self):
self.clips = []
self.num_video_tracks = 1
self.num_audio_tracks = 1
def add_clip(self, clip):
self.clips.append(clip)
self.clips.sort(key=lambda c: c.timeline_start_ms)
def get_total_duration(self):
if not self.clips: return 0
return max(c.timeline_end_ms for c in self.clips)
class TimelineWidget(QWidget):
TIMESCALE_HEIGHT = 30
HEADER_WIDTH = 120
TRACK_HEIGHT = 50
AUDIO_TRACKS_SEPARATOR_Y = 15
RESIZE_HANDLE_WIDTH = 8
SNAP_THRESHOLD_PIXELS = 8
split_requested = pyqtSignal(object)
delete_clip_requested = pyqtSignal(object)
delete_clips_requested = pyqtSignal(list)
playhead_moved = pyqtSignal(int)
split_region_requested = pyqtSignal(list)
split_all_regions_requested = pyqtSignal(list)
join_region_requested = pyqtSignal(list)
join_all_regions_requested = pyqtSignal(list)
delete_region_requested = pyqtSignal(list)
delete_all_regions_requested = pyqtSignal(list)
add_track = pyqtSignal(str)
remove_track = pyqtSignal(str)
operation_finished = pyqtSignal()
context_menu_requested = pyqtSignal(QMenu, 'QContextMenuEvent')
def __init__(self, timeline_model, settings, project_fps, parent=None):
super().__init__(parent)
self.timeline = timeline_model
self.settings = settings
self.playhead_pos_ms = 0
self.view_start_ms = 0
self.panning = False
self.pan_start_pos = QPoint()
self.pan_start_view_ms = 0
self.pixels_per_ms = 0.05
self.max_pixels_per_ms = 1.0
self.project_fps = 25.0
self.set_project_fps(project_fps)
self.setMinimumHeight(300)
self.setMouseTracking(True)
self.setAcceptDrops(True)
self.setFocusPolicy(Qt.FocusPolicy.StrongFocus)
self.selection_regions = []
self.selected_clips = set()
self.dragging_clip = None
self.dragging_linked_clip = None
self.dragging_playhead = False
self.creating_selection_region = False
self.dragging_selection_region = None
self.drag_start_pos = QPoint()
self.drag_original_clip_states = {}
self.selection_drag_start_ms = 0
self.drag_selection_start_values = None
self.drag_start_state = None
self.resizing_clip = None
self.resize_edge = None
self.resize_start_pos = QPoint()
self.resizing_selection_region = None
self.resize_selection_edge = None
self.resize_selection_start_values = None
self.highlighted_track_info = None
self.highlighted_ghost_track_info = None
self.add_video_track_btn_rect = QRect()
self.remove_video_track_btn_rect = QRect()
self.add_audio_track_btn_rect = QRect()
self.remove_audio_track_btn_rect = QRect()
self.video_tracks_y_start = 0
self.audio_tracks_y_start = 0
self.hover_preview_rect = None
self.hover_preview_audio_rect = None
self.drag_over_active = False
self.drag_over_rect = QRectF()
self.drag_over_audio_rect = QRectF()
self.drag_url_cache = {}
def set_hover_preview_rects(self, video_rect, audio_rect):
self.hover_preview_rect = video_rect
self.hover_preview_audio_rect = audio_rect
self.update()
def set_project_fps(self, fps):
self.project_fps = fps if fps > 0 else 25.0
self.max_pixels_per_ms = (self.project_fps * 20) / 1000.0
self.pixels_per_ms = min(self.pixels_per_ms, self.max_pixels_per_ms)
self.update()
def ms_to_x(self, ms): return self.HEADER_WIDTH + int(max(-500_000_000, min((ms - self.view_start_ms) * self.pixels_per_ms, 500_000_000)))
def x_to_ms(self, x): return self.view_start_ms + int(float(x - self.HEADER_WIDTH) / self.pixels_per_ms) if x > self.HEADER_WIDTH and self.pixels_per_ms > 0 else self.view_start_ms
def set_playhead_pos(self, time_ms):
self.playhead_pos_ms = time_ms
self.update()
def paintEvent(self, event):
painter = QPainter(self)
painter.setRenderHint(QPainter.RenderHint.Antialiasing)
painter.fillRect(self.rect(), QColor("#333"))
self.draw_headers(painter)
painter.save()
painter.setClipRect(self.HEADER_WIDTH, 0, self.width() - self.HEADER_WIDTH, self.height())
self.draw_timescale(painter)
self.draw_tracks_and_clips(painter)
self.draw_selections(painter)
if self.drag_over_active:
painter.setPen(QColor(0, 255, 0, 150))
if not self.drag_over_rect.isNull():
painter.fillRect(self.drag_over_rect, QColor(0, 255, 0, 80))
painter.drawRect(self.drag_over_rect)
if not self.drag_over_audio_rect.isNull():
painter.fillRect(self.drag_over_audio_rect, QColor(0, 255, 0, 80))
painter.drawRect(self.drag_over_audio_rect)
if self.hover_preview_rect:
painter.setPen(QPen(QColor(0, 255, 255, 180), 2, Qt.PenStyle.DashLine))
painter.fillRect(self.hover_preview_rect, QColor(0, 255, 255, 60))
painter.drawRect(self.hover_preview_rect)
if self.hover_preview_audio_rect:
painter.setPen(QPen(QColor(0, 255, 255, 180), 2, Qt.PenStyle.DashLine))
painter.fillRect(self.hover_preview_audio_rect, QColor(0, 255, 255, 60))
painter.drawRect(self.hover_preview_audio_rect)
self.draw_playhead(painter)
painter.restore()
total_height = self.calculate_total_height()
if self.minimumHeight() != total_height:
self.setMinimumHeight(total_height)
def calculate_total_height(self):
video_tracks_height = (self.timeline.num_video_tracks + 1) * self.TRACK_HEIGHT
audio_tracks_height = (self.timeline.num_audio_tracks + 1) * self.TRACK_HEIGHT
return self.TIMESCALE_HEIGHT + video_tracks_height + self.AUDIO_TRACKS_SEPARATOR_Y + audio_tracks_height + 20
def draw_headers(self, painter):
painter.save()
painter.setPen(QColor("#AAA"))
header_font = QFont("Arial", 9, QFont.Weight.Bold)
button_font = QFont("Arial", 8)
y_cursor = self.TIMESCALE_HEIGHT
rect = QRect(0, y_cursor, self.HEADER_WIDTH, self.TRACK_HEIGHT)
painter.fillRect(rect, QColor("#3a3a3a"))
painter.drawRect(rect)
self.add_video_track_btn_rect = QRect(rect.left() + 10, rect.top() + (rect.height() - 22)//2, self.HEADER_WIDTH - 20, 22)
painter.setFont(button_font)
painter.fillRect(self.add_video_track_btn_rect, QColor("#454"))
painter.drawText(self.add_video_track_btn_rect, Qt.AlignmentFlag.AlignCenter, "Add Track (+)")
y_cursor += self.TRACK_HEIGHT
self.video_tracks_y_start = y_cursor
for i in range(self.timeline.num_video_tracks):
track_number = self.timeline.num_video_tracks - i
rect = QRect(0, y_cursor, self.HEADER_WIDTH, self.TRACK_HEIGHT)
painter.fillRect(rect, QColor("#444"))
painter.drawRect(rect)
painter.setFont(header_font)
painter.drawText(rect, Qt.AlignmentFlag.AlignCenter, f"Video {track_number}")
if track_number == self.timeline.num_video_tracks and self.timeline.num_video_tracks > 1:
self.remove_video_track_btn_rect = QRect(rect.right() - 25, rect.top() + 5, 20, 20)
painter.setFont(button_font)
painter.fillRect(self.remove_video_track_btn_rect, QColor("#833"))
painter.drawText(self.remove_video_track_btn_rect, Qt.AlignmentFlag.AlignCenter, "-")
y_cursor += self.TRACK_HEIGHT
y_cursor += self.AUDIO_TRACKS_SEPARATOR_Y
self.audio_tracks_y_start = y_cursor
for i in range(self.timeline.num_audio_tracks):
track_number = i + 1
rect = QRect(0, y_cursor, self.HEADER_WIDTH, self.TRACK_HEIGHT)
painter.fillRect(rect, QColor("#444"))
painter.drawRect(rect)
painter.setFont(header_font)
painter.drawText(rect, Qt.AlignmentFlag.AlignCenter, f"Audio {track_number}")
if track_number == self.timeline.num_audio_tracks and self.timeline.num_audio_tracks > 1:
self.remove_audio_track_btn_rect = QRect(rect.right() - 25, rect.top() + 5, 20, 20)
painter.setFont(button_font)
painter.fillRect(self.remove_audio_track_btn_rect, QColor("#833"))
painter.drawText(self.remove_audio_track_btn_rect, Qt.AlignmentFlag.AlignCenter, "-")
y_cursor += self.TRACK_HEIGHT
rect = QRect(0, y_cursor, self.HEADER_WIDTH, self.TRACK_HEIGHT)
painter.fillRect(rect, QColor("#3a3a3a"))
painter.drawRect(rect)
self.add_audio_track_btn_rect = QRect(rect.left() + 10, rect.top() + (rect.height() - 22)//2, self.HEADER_WIDTH - 20, 22)
painter.setFont(button_font)
painter.fillRect(self.add_audio_track_btn_rect, QColor("#454"))
painter.drawText(self.add_audio_track_btn_rect, Qt.AlignmentFlag.AlignCenter, "Add Track (+)")
painter.restore()
def _format_timecode(self, total_ms, interval_ms):
if abs(total_ms) < 1: total_ms = 0
sign = "-" if total_ms < 0 else ""
total_ms = abs(total_ms)
seconds = total_ms / 1000.0
# Frame-based formatting for high zoom
is_frame_based = interval_ms < (1000.0 / self.project_fps) * 5
if is_frame_based:
total_frames = int(round(seconds * self.project_fps))
fps_int = int(round(self.project_fps))
if fps_int == 0: fps_int = 25 # Avoid division by zero
s_frames = total_frames % fps_int
total_seconds_from_frames = total_frames // fps_int
h_fr = total_seconds_from_frames // 3600
m_fr = (total_seconds_from_frames % 3600) // 60
s_fr = total_seconds_from_frames % 60
if h_fr > 0: return f"{sign}{h_fr}:{m_fr:02d}:{s_fr:02d}:{s_frames:02d}"
if m_fr > 0: return f"{sign}{m_fr}:{s_fr:02d}:{s_frames:02d}"
return f"{sign}{s_fr}:{s_frames:02d}"
# Sub-second formatting
if interval_ms < 1000:
precision = 2 if interval_ms < 100 else 1
s_float = seconds % 60
m = int((seconds % 3600) / 60)
h = int(seconds / 3600)
if h > 0: return f"{sign}{h}:{m:02d}:{s_float:0{4+precision}.{precision}f}"
if m > 0: return f"{sign}{m}:{s_float:0{4+precision}.{precision}f}"
val = f"{s_float:.{precision}f}"
if '.' in val: val = val.rstrip('0').rstrip('.')
return f"{sign}{val}s"
# Seconds and M:SS formatting
if interval_ms < 60000:
rounded_seconds = int(round(seconds))
h = rounded_seconds // 3600
m = (rounded_seconds % 3600) // 60
s = rounded_seconds % 60
if h > 0:
return f"{sign}{h}:{m:02d}:{s:02d}"
# Use "Xs" format for times under a minute
if rounded_seconds < 60:
return f"{sign}{rounded_seconds}s"
# Use "M:SS" format for times over a minute
return f"{sign}{m}:{s:02d}"
# Minute and Hh:MMm formatting for low zoom
h = int(seconds / 3600)
m = int((seconds % 3600) / 60)
if h > 0: return f"{sign}{h}h:{m:02d}m"
total_minutes = int(seconds / 60)
return f"{sign}{total_minutes}m"
def draw_timescale(self, painter):
painter.save()
painter.setPen(QColor("#AAA"))
painter.setFont(QFont("Arial", 8))
font_metrics = QFontMetrics(painter.font())
painter.fillRect(QRect(self.HEADER_WIDTH, 0, self.width() - self.HEADER_WIDTH, self.TIMESCALE_HEIGHT), QColor("#222"))
painter.drawLine(self.HEADER_WIDTH, self.TIMESCALE_HEIGHT - 1, self.width(), self.TIMESCALE_HEIGHT - 1)
frame_dur_ms = 1000.0 / self.project_fps
intervals_ms = [
frame_dur_ms, 2*frame_dur_ms, 5*frame_dur_ms, 10*frame_dur_ms,
100, 200, 500, 1000, 2000, 5000, 10000, 15000, 30000,
60000, 120000, 300000, 600000, 900000, 1800000,
3600000, 2*3600000, 5*3600000, 10*3600000
]
min_pixel_dist = 70
major_interval = next((i for i in intervals_ms if i * self.pixels_per_ms > min_pixel_dist), intervals_ms[-1])
minor_interval = 0
for divisor in [5, 4, 2]:
if (major_interval / divisor) * self.pixels_per_ms > 10:
minor_interval = major_interval / divisor
break
start_ms = self.x_to_ms(self.HEADER_WIDTH)
end_ms = self.x_to_ms(self.width())
def draw_ticks(interval_ms, height):
if interval_ms < 1: return
start_tick_num = int(start_ms / interval_ms)
end_tick_num = int(end_ms / interval_ms) + 1
for i in range(start_tick_num, end_tick_num + 1):
t_ms = i * interval_ms
x = self.ms_to_x(t_ms)
if x > self.width(): break
if x >= self.HEADER_WIDTH:
painter.drawLine(x, self.TIMESCALE_HEIGHT - height, x, self.TIMESCALE_HEIGHT)
if frame_dur_ms * self.pixels_per_ms > 4:
draw_ticks(frame_dur_ms, 3)
if minor_interval > 0:
draw_ticks(minor_interval, 6)
start_major_tick = int(start_ms / major_interval)
end_major_tick = int(end_ms / major_interval) + 1
for i in range(start_major_tick, end_major_tick + 1):
t_ms = i * major_interval
x = self.ms_to_x(t_ms)
if x > self.width() + 50: break
if x >= self.HEADER_WIDTH - 50:
painter.drawLine(x, self.TIMESCALE_HEIGHT - 12, x, self.TIMESCALE_HEIGHT)
label = self._format_timecode(t_ms, major_interval)
label_width = font_metrics.horizontalAdvance(label)
label_x = x - label_width // 2
if label_x < self.HEADER_WIDTH:
label_x = self.HEADER_WIDTH
painter.drawText(label_x, self.TIMESCALE_HEIGHT - 14, label)
painter.restore()
def get_clip_rect(self, clip):
if clip.track_type == 'video':
visual_index = self.timeline.num_video_tracks - clip.track_index
y = self.video_tracks_y_start + visual_index * self.TRACK_HEIGHT
else:
visual_index = clip.track_index - 1
y = self.audio_tracks_y_start + visual_index * self.TRACK_HEIGHT
x = self.ms_to_x(clip.timeline_start_ms)
w = int(clip.duration_ms * self.pixels_per_ms)
clip_height = self.TRACK_HEIGHT - 10
y += (self.TRACK_HEIGHT - clip_height) / 2
return QRectF(x, y, w, clip_height)
def draw_tracks_and_clips(self, painter):
painter.save()
y_cursor = self.video_tracks_y_start
for i in range(self.timeline.num_video_tracks):
rect = QRect(self.HEADER_WIDTH, y_cursor, self.width() - self.HEADER_WIDTH, self.TRACK_HEIGHT)
painter.fillRect(rect, QColor("#444") if i % 2 == 0 else QColor("#404040"))
y_cursor += self.TRACK_HEIGHT
y_cursor = self.audio_tracks_y_start
for i in range(self.timeline.num_audio_tracks):
rect = QRect(self.HEADER_WIDTH, y_cursor, self.width() - self.HEADER_WIDTH, self.TRACK_HEIGHT)
painter.fillRect(rect, QColor("#444") if i % 2 == 0 else QColor("#404040"))
y_cursor += self.TRACK_HEIGHT
if self.highlighted_track_info:
track_type, track_index = self.highlighted_track_info
y = -1
if track_type == 'video' and track_index <= self.timeline.num_video_tracks:
visual_index = self.timeline.num_video_tracks - track_index
y = self.video_tracks_y_start + visual_index * self.TRACK_HEIGHT
elif track_type == 'audio' and track_index <= self.timeline.num_audio_tracks:
visual_index = track_index - 1
y = self.audio_tracks_y_start + visual_index * self.TRACK_HEIGHT
if y != -1:
highlight_rect = QRect(self.HEADER_WIDTH, int(y), self.width() - self.HEADER_WIDTH, self.TRACK_HEIGHT)
painter.fillRect(highlight_rect, QColor(255, 255, 0, 40))
if self.highlighted_ghost_track_info:
track_type, track_index = self.highlighted_ghost_track_info
y = -1
if track_type == 'video':
y = self.TIMESCALE_HEIGHT
elif track_type == 'audio':
y = self.audio_tracks_y_start + self.timeline.num_audio_tracks * self.TRACK_HEIGHT
if y != -1:
highlight_rect = QRect(self.HEADER_WIDTH, int(y), self.width() - self.HEADER_WIDTH, self.TRACK_HEIGHT)
painter.fillRect(highlight_rect, QColor(255, 255, 0, 40))
for clip in self.timeline.clips:
clip_rect = self.get_clip_rect(clip)
base_color = QColor("#46A")
if clip.media_type == 'image':
base_color = QColor("#4A6")
elif clip.media_type == 'subtitle':
base_color = QColor("#D9A022")
elif clip.track_type == 'audio':
base_color = QColor("#48C")
color = QColor("#5A9") if self.dragging_clip and self.dragging_clip.id == clip.id else base_color
painter.fillRect(clip_rect, color)
if clip.id in self.selected_clips:
pen = QPen(QColor(255, 255, 0, 220), 2)
painter.setPen(pen)
painter.drawRect(clip_rect)
painter.setPen(QPen(QColor("#FFF"), 1))
font = QFont("Arial", 10)
painter.setFont(font)
text = os.path.basename(clip.source_path)
font_metrics = QFontMetrics(font)
text_width = font_metrics.horizontalAdvance(text)
if text_width > clip_rect.width() - 10: text = font_metrics.elidedText(text, Qt.TextElideMode.ElideRight, int(clip_rect.width() - 10))
painter.drawText(QPoint(int(clip_rect.left() + 5), int(clip_rect.center().y() + 5)), text)
painter.restore()
def draw_selections(self, painter):
for start_ms, end_ms in self.selection_regions:
x = self.ms_to_x(start_ms)
w = int((end_ms - start_ms) * self.pixels_per_ms)
selection_rect = QRectF(x, self.TIMESCALE_HEIGHT, w, self.height() - self.TIMESCALE_HEIGHT)
painter.fillRect(selection_rect, QColor(100, 100, 255, 80))
painter.setPen(QColor(150, 150, 255, 150))
painter.drawRect(selection_rect)
def draw_playhead(self, painter):
playhead_x = self.ms_to_x(self.playhead_pos_ms)
painter.setPen(QPen(QColor("red"), 2))
painter.drawLine(playhead_x, 0, playhead_x, self.height())
def y_to_track_info(self, y):
if self.TIMESCALE_HEIGHT <= y < self.video_tracks_y_start:
return ('video', self.timeline.num_video_tracks + 1)
video_tracks_end_y = self.video_tracks_y_start + self.timeline.num_video_tracks * self.TRACK_HEIGHT
if self.video_tracks_y_start <= y < video_tracks_end_y:
visual_index = (y - self.video_tracks_y_start) // self.TRACK_HEIGHT
track_index = self.timeline.num_video_tracks - visual_index
return ('video', track_index)
audio_tracks_end_y = self.audio_tracks_y_start + self.timeline.num_audio_tracks * self.TRACK_HEIGHT
if self.audio_tracks_y_start <= y < audio_tracks_end_y:
visual_index = (y - self.audio_tracks_y_start) // self.TRACK_HEIGHT
track_index = visual_index + 1
return ('audio', track_index)
add_audio_btn_y_start = self.audio_tracks_y_start + self.timeline.num_audio_tracks * self.TRACK_HEIGHT
add_audio_btn_y_end = add_audio_btn_y_start + self.TRACK_HEIGHT
if add_audio_btn_y_start <= y < add_audio_btn_y_end:
return ('audio', self.timeline.num_audio_tracks + 1)
return None
def _snap_to_frame(self, time_ms):
frame_duration_ms = 1000.0 / self.project_fps
if frame_duration_ms <= 0:
return int(time_ms)
frame_number = round(time_ms / frame_duration_ms)
return int(frame_number * frame_duration_ms)
def _snap_time_if_needed(self, time_ms):
frame_duration_ms = 1000.0 / self.project_fps
if frame_duration_ms > 0 and frame_duration_ms * self.pixels_per_ms > 4:
return self._snap_to_frame(time_ms)
return int(time_ms)
def get_region_at_pos(self, pos: QPoint):
if pos.y() <= self.TIMESCALE_HEIGHT or pos.x() <= self.HEADER_WIDTH:
return None
clicked_ms = self.x_to_ms(pos.x())
for region in reversed(self.selection_regions):
if region[0] <= clicked_ms <= region[1]:
return region
return None
def wheelEvent(self, event: QMouseEvent):
delta = event.angleDelta().y()
zoom_factor = 1.15
old_pps = self.pixels_per_ms
if delta > 0:
new_pps = old_pps * zoom_factor
else:
new_pps = old_pps / zoom_factor
min_pps = 1 / (3600 * 10 * 1000)
new_pps = max(min_pps, min(new_pps, self.max_pixels_per_ms))
if abs(new_pps - old_pps) < 1e-9:
return
if event.position().x() < self.HEADER_WIDTH:
new_view_start_ms = self.view_start_ms * (old_pps / new_pps)
else:
mouse_x = event.position().x()
time_at_cursor = self.x_to_ms(mouse_x)
new_view_start_ms = time_at_cursor - (mouse_x - self.HEADER_WIDTH) / new_pps
self.pixels_per_ms = new_pps
self.view_start_ms = int(max(0, new_view_start_ms))
self.update()
event.accept()
def mousePressEvent(self, event: QMouseEvent):
if event.button() == Qt.MouseButton.MiddleButton:
self.panning = True
self.pan_start_pos = event.pos()
self.pan_start_view_ms = self.view_start_ms
self.setCursor(Qt.CursorShape.ClosedHandCursor)
event.accept()
return
if event.pos().x() < self.HEADER_WIDTH:
if self.add_video_track_btn_rect.contains(event.pos()): self.add_track.emit('video')
elif self.remove_video_track_btn_rect.contains(event.pos()): self.remove_track.emit('video')
elif self.add_audio_track_btn_rect.contains(event.pos()): self.add_track.emit('audio')
elif self.remove_audio_track_btn_rect.contains(event.pos()): self.remove_track.emit('audio')
return
if event.button() == Qt.MouseButton.LeftButton:
self.setFocus()
self.dragging_clip = None
self.dragging_linked_clip = None
self.dragging_playhead = False
self.creating_selection_region = False
self.dragging_selection_region = None
self.resizing_clip = None
self.resize_edge = None
self.drag_original_clip_states.clear()
self.resizing_selection_region = None
self.resize_selection_edge = None
self.resize_selection_start_values = None
for region in self.selection_regions:
if not region: continue
x_start = self.ms_to_x(region[0])
x_end = self.ms_to_x(region[1])
if event.pos().y() > self.TIMESCALE_HEIGHT:
if abs(event.pos().x() - x_start) < self.RESIZE_HANDLE_WIDTH:
self.resizing_selection_region = region
self.resize_selection_edge = 'left'
break
elif abs(event.pos().x() - x_end) < self.RESIZE_HANDLE_WIDTH:
self.resizing_selection_region = region
self.resize_selection_edge = 'right'
break
if self.resizing_selection_region:
self.resize_selection_start_values = tuple(self.resizing_selection_region)
self.drag_start_pos = event.pos()
self.update()
return
for clip in reversed(self.timeline.clips):
clip_rect = self.get_clip_rect(clip)
if abs(event.pos().x() - clip_rect.left()) < self.RESIZE_HANDLE_WIDTH and clip_rect.contains(QPointF(clip_rect.left(), event.pos().y())):
self.resizing_clip = clip
self.resize_edge = 'left'
break
elif abs(event.pos().x() - clip_rect.right()) < self.RESIZE_HANDLE_WIDTH and clip_rect.contains(QPointF(clip_rect.right(), event.pos().y())):
self.resizing_clip = clip
self.resize_edge = 'right'
break
if self.resizing_clip:
self.drag_start_state = self.window()._get_current_timeline_state()
self.resize_start_pos = event.pos()
self.update()
return
clicked_clip = None
for clip in reversed(self.timeline.clips):
if self.get_clip_rect(clip).contains(QPointF(event.pos())):
clicked_clip = clip
break
if clicked_clip:
is_ctrl_pressed = bool(event.modifiers() & Qt.KeyboardModifier.ControlModifier)
if clicked_clip.id in self.selected_clips:
if is_ctrl_pressed:
self.selected_clips.remove(clicked_clip.id)
else:
if not is_ctrl_pressed:
self.selected_clips.clear()
self.selected_clips.add(clicked_clip.id)
if clicked_clip.id in self.selected_clips:
self.dragging_clip = clicked_clip
self.drag_start_state = self.window()._get_current_timeline_state()
self.drag_original_clip_states[clicked_clip.id] = (clicked_clip.timeline_start_ms, clicked_clip.track_index)
self.dragging_linked_clip = next((c for c in self.timeline.clips if c.group_id == clicked_clip.group_id and c.id != clicked_clip.id), None)
if self.dragging_linked_clip:
self.drag_original_clip_states[self.dragging_linked_clip.id] = \
(self.dragging_linked_clip.timeline_start_ms, self.dragging_linked_clip.track_index)
self.drag_start_pos = event.pos()
else:
self.selected_clips.clear()
region_to_drag = self.get_region_at_pos(event.pos())
if region_to_drag:
self.dragging_selection_region = region_to_drag
self.drag_start_pos = event.pos()
self.drag_selection_start_values = tuple(region_to_drag)
else:
is_on_timescale = event.pos().y() <= self.TIMESCALE_HEIGHT
is_in_track_area = event.pos().y() > self.TIMESCALE_HEIGHT and event.pos().x() > self.HEADER_WIDTH
if is_in_track_area:
self.creating_selection_region = True
is_shift_pressed = bool(event.modifiers() & Qt.KeyboardModifier.ShiftModifier)
start_ms = self.x_to_ms(event.pos().x())
if is_shift_pressed:
self.selection_drag_start_ms = self._snap_to_frame(start_ms)
else:
playhead_x = self.ms_to_x(self.playhead_pos_ms)
if abs(event.pos().x() - playhead_x) < self.SNAP_THRESHOLD_PIXELS:
self.selection_drag_start_ms = self.playhead_pos_ms
else:
self.selection_drag_start_ms = start_ms
self.selection_regions.append([self.selection_drag_start_ms, self.selection_drag_start_ms])
elif is_on_timescale:
time_ms = max(0, self.x_to_ms(event.pos().x()))
if event.modifiers() & Qt.KeyboardModifier.ShiftModifier:
self.playhead_pos_ms = self._snap_to_frame(time_ms)
else:
self.playhead_pos_ms = self._snap_time_if_needed(time_ms)
self.playhead_moved.emit(self.playhead_pos_ms)
self.dragging_playhead = True
self.update()
def mouseMoveEvent(self, event: QMouseEvent):
if self.panning:
delta_x = event.pos().x() - self.pan_start_pos.x()
time_delta = delta_x / self.pixels_per_ms
new_view_start = self.pan_start_view_ms - time_delta
self.view_start_ms = int(max(0, new_view_start))
self.update()
return
if self.resizing_selection_region:
current_ms = max(0, self.x_to_ms(event.pos().x()))
if event.modifiers() & Qt.KeyboardModifier.ShiftModifier:
current_ms = self._snap_to_frame(current_ms)
original_start, original_end = self.resize_selection_start_values
if self.resize_selection_edge == 'left':
new_start = current_ms
new_end = original_end
else: # right
new_start = original_start
new_end = current_ms
self.resizing_selection_region[0] = min(new_start, new_end)
self.resizing_selection_region[1] = max(new_start, new_end)
if (self.resize_selection_edge == 'left' and new_start > new_end) or \
(self.resize_selection_edge == 'right' and new_end < new_start):
self.resize_selection_edge = 'right' if self.resize_selection_edge == 'left' else 'left'
self.resize_selection_start_values = (original_end, original_start)
self.update()
return
if self.resizing_clip:
is_shift_pressed = bool(event.modifiers() & Qt.KeyboardModifier.ShiftModifier)
linked_clip = next((c for c in self.timeline.clips if c.group_id == self.resizing_clip.group_id and c.id != self.resizing_clip.id), None)
delta_x = event.pos().x() - self.resize_start_pos.x()
time_delta = delta_x / self.pixels_per_ms
min_duration_ms = int(1000 / self.project_fps)
snap_time_delta = self.SNAP_THRESHOLD_PIXELS / self.pixels_per_ms
snap_points = [self.playhead_pos_ms]
for clip in self.timeline.clips:
if clip.id == self.resizing_clip.id: continue
if linked_clip and clip.id == linked_clip.id: continue
snap_points.append(clip.timeline_start_ms)
snap_points.append(clip.timeline_end_ms)
media_props = self.window().media_properties.get(self.resizing_clip.source_path)
source_duration_ms = media_props['duration_ms'] if media_props else float('inf')
if self.resize_edge == 'left':
original_start = self.drag_start_state[0][[c.id for c in self.drag_start_state[0]].index(self.resizing_clip.id)].timeline_start_ms
original_duration = self.drag_start_state[0][[c.id for c in self.drag_start_state[0]].index(self.resizing_clip.id)].duration_ms
original_clip_start = self.drag_start_state[0][[c.id for c in self.drag_start_state[0]].index(self.resizing_clip.id)].clip_start_ms
true_new_start_ms = original_start + time_delta
if is_shift_pressed:
new_start_ms = self._snap_to_frame(true_new_start_ms)
else:
new_start_ms = true_new_start_ms
for snap_point in snap_points:
if abs(true_new_start_ms - snap_point) < snap_time_delta:
new_start_ms = snap_point
break
if new_start_ms > original_start + original_duration - min_duration_ms:
new_start_ms = original_start + original_duration - min_duration_ms
new_start_ms = max(0, new_start_ms)
if self.resizing_clip.media_type != 'image':
if new_start_ms < original_start - original_clip_start:
new_start_ms = original_start - original_clip_start
new_duration = (original_start + original_duration) - new_start_ms
new_clip_start = original_clip_start + (new_start_ms - original_start)