-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathVideoCompression.py
More file actions
4526 lines (3722 loc) Β· 219 KB
/
VideoCompression.py
File metadata and controls
4526 lines (3722 loc) Β· 219 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
#!/usr/bin/env python3
import os
import sys
import json
import subprocess
import shutil
import tempfile
import time
import logging
import logging.handlers
from datetime import datetime, timedelta
from pathlib import Path
import hashlib
import argparse
import psutil
import queue
import threading
import re
import platform
from concurrent.futures import ThreadPoolExecutor, as_completed
from multiprocessing import cpu_count
import statistics
class WorkerGenerator:
"""Generator-based worker system for efficient task processing and worker reuse."""
def __init__(self, worker_id, compressor_instance):
self.worker_id = worker_id
self.compressor = compressor_instance
self.active = True
self.tasks_completed = 0
def segment_compression_generator(self):
"""Generator that yields segment compression results efficiently."""
while self.active:
try:
# Wait for task from queue (this will be yielded to)
task = yield
if task is None: # Shutdown signal
break
self.tasks_completed += 1
segment_path = task['segment_path']
segment_index = task['segment_index']
total_segments = task['total_segments']
file_path = task['file_path']
self.compressor.log(f"π¬ [{self.worker_id}] Processing segment {segment_index+1}/{total_segments}", "DEBUG")
# Create output path for compressed segment
segment_path_obj = Path(segment_path)
output_dir = segment_path_obj.parent
output_path = output_dir / f"{segment_path_obj.stem}_compressed{segment_path_obj.suffix}"
# Get video info and settings for compression
original_info = self.compressor.get_video_info(file_path)
settings = self.compressor.get_compression_settings()
# Compress the segment
success, message = self.compressor.compress_single_file(
segment_path, output_path, original_info, settings,
progress_callback=lambda p: None # Individual segment progress
)
# Clean up original segment if successful
if success:
try:
Path(segment_path).unlink()
self.compressor.log(f"π§Ή [{self.worker_id}] Cleaned up original segment: {segment_path_obj.name}", "DEBUG")
except Exception as cleanup_e:
self.compressor.log(f"β οΈ [{self.worker_id}] Failed to clean up segment: {cleanup_e}", "WARNING")
# Yield result back to caller
yield {
'success': success,
'segment_path': segment_path,
'output_path': output_path,
'message': message,
'worker_id': self.worker_id,
'tasks_completed': self.tasks_completed
}
except Exception as e:
error_msg = f"Generator worker error: {type(e).__name__}: {e}"
self.compressor.log(f"β [{self.worker_id}] {error_msg}", "ERROR")
yield {
'success': False,
'error': error_msg,
'worker_id': self.worker_id
}
def small_file_generator(self):
"""Generator for processing small files efficiently."""
while self.active:
try:
# Wait for task from queue
task = yield
if task is None: # Shutdown signal
break
self.tasks_completed += 1
file_path = task['file_path']
file_name = Path(file_path).name
self.compressor.log(f"π¬ [{self.worker_id}] Processing small file: {file_name}", "DEBUG")
# Process the file using existing compression logic
success, message = self.compressor.compress_video(file_path)
yield {
'success': success,
'file_path': file_path,
'message': message,
'worker_id': self.worker_id,
'tasks_completed': self.tasks_completed
}
except Exception as e:
error_msg = f"Small file generator error: {type(e).__name__}: {e}"
self.compressor.log(f"β [{self.worker_id}] {error_msg}", "ERROR")
yield {
'success': False,
'file_path': task.get('file_path', 'unknown'),
'error': error_msg,
'worker_id': self.worker_id
}
def shutdown(self):
"""Signal the generator to shutdown gracefully."""
self.active = False
class CompressionAnalytics:
"""Tracks compression efficiency metrics and performance data."""
def __init__(self):
self.compression_stats = {
'total_files_processed': 0,
'total_size_reduction': 0,
'average_compression_ratio': 0.0,
'processing_time_seconds': 0.0,
'throughput_mbps': 0.0,
'efficiency_score': 0.0
}
self.session_start_time = time.time()
self.file_metrics = []
def track_compression(self, original_size, compressed_size, processing_time, file_path):
"""Track metrics for a single file compression."""
size_reduction = original_size - compressed_size
compression_ratio = compressed_size / original_size if original_size > 0 else 1.0
throughput = (original_size / (1024 * 1024)) / max(processing_time, 0.1) # MB/s
# Update aggregate stats
self.compression_stats['total_files_processed'] += 1
self.compression_stats['total_size_reduction'] += size_reduction
self.compression_stats['processing_time_seconds'] += processing_time
# Recalculate averages
total_files = self.compression_stats['total_files_processed']
self.compression_stats['average_compression_ratio'] = sum(
metric['compression_ratio'] for metric in self.file_metrics
) / total_files if total_files > 0 else 1.0
# Calculate overall throughput
total_time = time.time() - self.session_start_time
total_size_mb = sum(metric['original_size'] for metric in self.file_metrics) / (1024 * 1024)
self.compression_stats['throughput_mbps'] = total_size_mb / max(total_time, 0.1)
# Store individual file metrics
file_metric = {
'file_path': str(file_path),
'original_size': original_size,
'compressed_size': compressed_size,
'size_reduction': size_reduction,
'compression_ratio': compression_ratio,
'processing_time': processing_time,
'throughput_mbps': throughput,
'timestamp': time.time()
}
self.file_metrics.append(file_metric)
# Calculate efficiency score (combination of compression ratio and speed)
efficiency = (1 - compression_ratio) * (min(throughput / 10, 1.0)) # Normalized efficiency
self.compression_stats['efficiency_score'] = sum(
metric.get('efficiency', 0) for metric in self.file_metrics
) / total_files if total_files > 0 else 0.0
return file_metric
def get_summary(self):
"""Get comprehensive analytics summary."""
return {
'stats': self.compression_stats.copy(),
'recent_files': self.file_metrics[-5:] if self.file_metrics else [],
'session_duration': time.time() - self.session_start_time
}
class GeneratorWorkerManager:
"""Manages generator-based workers for efficient task distribution."""
def __init__(self, compressor_instance, max_workers=None):
self.compressor = compressor_instance
self.max_workers = max_workers or compressor_instance.max_concurrent_jobs
self.generators = {}
self.active_generators = []
def create_segment_workers(self):
"""Create and initialize segment compression generator workers."""
self.active_generators = []
for i in range(self.max_workers):
worker_id = f"GenWorker-{i+1}"
worker = WorkerGenerator(worker_id, self.compressor)
generator = worker.segment_compression_generator()
next(generator) # Initialize generator (first yield)
self.generators[worker_id] = {
'worker': worker,
'generator': generator,
'type': 'segment'
}
self.active_generators.append(worker_id)
self.compressor.log(f"π Created {len(self.active_generators)} generator-based segment workers", "INFO")
def process_segments_with_generators(self, segment_tasks, progress_callback=None, max_retries=2):
"""Process segments using reusable generator workers with enhanced error recovery."""
completed_segments = []
failed_segments = []
retry_queue = [] # Tasks that need to be retried
# Create workers if not already created
if not self.active_generators:
self.create_segment_workers()
# Distribute tasks among generators with retry tracking
task_queue = [(task, 0) for task in segment_tasks] # (task, retry_count)
worker_index = 0
while task_queue or retry_queue or any(gen['generator'] for gen in self.generators.values()):
# Process retry queue first
if retry_queue and not task_queue:
task_queue = retry_queue[:]
retry_queue.clear()
self.compressor.log(f"π Processing {len(task_queue)} retry tasks", "INFO")
# Assign tasks to available generators
for worker_id in self.active_generators[:]: # Copy list to allow modification
if not task_queue:
break
generator_info = self.generators[worker_id]
generator = generator_info['generator']
try:
# Send task to generator
task_data, retry_count = task_queue.pop(0)
result = generator.send(task_data)
# Process result with retry logic
if result['success']:
completed_segments.append(result['output_path'])
self.compressor.log(f"β
Generator completed segment: {Path(result['segment_path']).name}", "DEBUG")
else:
if retry_count < max_retries:
# Add to retry queue
retry_queue.append((task_data, retry_count + 1))
self.compressor.log(f"π Retrying segment {Path(result['segment_path']).name} (attempt {retry_count + 2}/{max_retries + 1})", "WARNING")
else:
# Max retries exceeded
failed_segments.append({
'segment_path': result['segment_path'],
'error': f"Max retries ({max_retries}) exceeded: {result.get('message', 'Unknown error')}"
})
self.compressor.log(f"β Generator permanently failed segment after {max_retries} retries: {result.get('message', 'Unknown error')}", "ERROR")
# Update progress accounting for retries
if progress_callback:
total_processed = len(completed_segments) + len(failed_segments)
total_tasks = len(segment_tasks)
remaining_retries = len(retry_queue)
# Provide detailed progress info
progress_info = {
'completed': len(completed_segments),
'failed': len(failed_segments),
'retries_pending': remaining_retries,
'total_tasks': total_tasks,
'progress': total_processed / total_tasks if total_tasks > 0 else 0
}
try:
progress_callback(progress_info['progress'])
except TypeError:
# Fallback for simple progress callbacks
progress_callback(total_processed / total_tasks if total_tasks > 0 else 0)
except StopIteration:
# Generator exhausted, remove from active list
self.active_generators.remove(worker_id)
self.compressor.log(f"π Generator {worker_id} completed all tasks", "DEBUG")
except Exception as e:
self.compressor.log(f"β Generator {worker_id} error: {e}", "ERROR")
self.active_generators.remove(worker_id)
return completed_segments, failed_segments
def shutdown_all(self):
"""Shutdown all generator workers gracefully."""
for worker_id, generator_info in self.generators.items():
try:
worker = generator_info['worker']
generator = generator_info['generator']
worker.shutdown()
generator.send(None) # Send shutdown signal
except (StopIteration, GeneratorExit):
pass # Expected when shutting down
except Exception as e:
self.compressor.log(f"β οΈ Error shutting down generator {worker_id}: {e}", "WARNING")
self.generators.clear()
self.active_generators.clear()
self.compressor.log(f"π All generator workers shutdown", "INFO")
class ProgressAggregator:
"""Thread-safe progress aggregator for complex video processing workflows."""
def __init__(self, config=None):
self._lock = threading.RLock()
self._workers = {} # worker_id -> worker_info
self._start_time = time.time()
self._total_bytes = 0
self._processed_bytes = 0
self._callback = None
self._notifying = False # Prevent recursion in callback notifications
self._last_callback_time = 0 # Throttle callback frequency
# Enhanced tracking for Stage 3
self._active_thread_count = 0 # Actual active ThreadPoolExecutor workers
self._total_thread_count = 0 # Total ThreadPoolExecutor workers
self._queue_size = 0 # Remaining tasks in queue
self._total_queue_size = 0 # Initial queue size
self._current_file_index = 0 # Current file being processed
self._total_files = 0 # Total files to process
# Get callback interval from config or use default
if config and 'large_file_settings' in config:
self._callback_interval = config['large_file_settings'].get('ui_callback_interval_seconds', 0.5)
else:
self._callback_interval = 0.5 # Default fallback
def register_worker(self, worker_id, task_name, file_size_bytes=0, segment_info=None):
"""Register a new worker/task with the aggregator."""
with self._lock:
self._workers[worker_id] = {
'task_name': task_name,
'file_size_bytes': file_size_bytes,
'processed_bytes': 0,
'progress_pct': 0.0,
'fps': 0.0,
'status': 'starting',
'start_time': time.time(),
'last_update': time.time(),
'segment_info': segment_info, # {'current': 1, 'total': 5, 'duration': 300}
'throughput_mbps': 0.0,
'eta_seconds': 0
}
self._total_bytes += file_size_bytes
def update_worker_progress(self, worker_id, progress_pct, fps=0.0, processed_bytes=None):
"""Update progress for a specific worker with robust type checking."""
with self._lock:
if worker_id not in self._workers:
return
worker = self._workers[worker_id]
old_progress = worker['progress_pct']
# Robust type checking for progress_pct - handle dictionary objects
if isinstance(progress_pct, dict):
# Extract progress percentage from dictionary if available
if 'overall_progress' in progress_pct:
progress_value = progress_pct['overall_progress']
elif 'progress' in progress_pct:
progress_value = progress_pct['progress']
elif 'percent' in progress_pct:
progress_value = progress_pct['percent']
else:
# Log warning and use previous value
if hasattr(self, 'log'):
self.log(f"Warning: Progress data for {worker_id} is dict without progress field: {progress_pct}", "WARNING")
progress_value = old_progress
elif isinstance(progress_pct, (int, float)) and not isinstance(progress_pct, bool):
progress_value = progress_pct
else:
# Handle invalid types - log and use previous value
if hasattr(self, 'log'):
self.log(f"Warning: Invalid progress type for {worker_id}: {type(progress_pct)} = {progress_pct}", "WARNING")
progress_value = old_progress
# Ensure progress_value is numeric and clamp to valid range
try:
progress_value = float(progress_value) if progress_value is not None else 0.0
progress_value = max(0.0, min(progress_value, 1.0))
except (ValueError, TypeError):
progress_value = old_progress
if hasattr(self, 'log'):
self.log(f"Warning: Could not convert progress to float for {worker_id}, keeping previous: {old_progress}", "WARNING")
worker['progress_pct'] = progress_value
# Type check fps parameter
try:
fps_value = float(fps) if isinstance(fps, (int, float)) and not isinstance(fps, bool) else 0.0
fps_value = max(0.0, fps_value) # Ensure non-negative
except (ValueError, TypeError):
fps_value = 0.0
worker['fps'] = fps_value
worker['last_update'] = time.time()
worker['status'] = 'processing' if progress_value < 1.0 else 'completed'
# Calculate processed bytes if not provided
if processed_bytes is not None:
# Type check processed_bytes parameter
try:
processed_value = float(processed_bytes) if isinstance(processed_bytes, (int, float)) and not isinstance(processed_bytes, bool) else None
if processed_value is not None and processed_value >= 0:
old_processed = worker['processed_bytes']
worker['processed_bytes'] = processed_value
self._processed_bytes += (processed_value - old_processed)
else:
# Invalid processed_bytes, fall through to estimation
processed_bytes = None
except (ValueError, TypeError):
# Invalid processed_bytes, fall through to estimation
processed_bytes = None
if processed_bytes is None:
# Estimate based on progress percentage
new_processed = worker['file_size_bytes'] * progress_value
old_processed = worker['processed_bytes']
worker['processed_bytes'] = new_processed
self._processed_bytes += (new_processed - old_processed)
# Calculate throughput (MB/s)
elapsed = time.time() - worker['start_time']
if elapsed > 0:
bytes_processed = worker['processed_bytes']
worker['throughput_mbps'] = (bytes_processed / (1024 * 1024)) / elapsed
# Calculate ETA for this worker
if progress_value > 0.01:
try:
total_time_est = elapsed / progress_value
calculated_eta = max(0, total_time_est - elapsed)
# Ensure eta_seconds is always a number
worker['eta_seconds'] = float(calculated_eta) if isinstance(calculated_eta, (int, float)) else 0.0
except (TypeError, ValueError, ZeroDivisionError):
worker['eta_seconds'] = 0.0
# Notify callback after any progress update to keep UI responsive
self.notify_callback()
def get_aggregate_progress(self):
"""Get overall progress across all workers."""
with self._lock:
if self._total_bytes == 0:
return {
'overall_progress': 0.0,
'active_workers': 0,
'total_workers': len(self._workers),
'throughput_mbps': 0.0,
'eta_seconds': 0,
'workers': []
}
# Calculate weighted average progress
total_weighted_progress = 0.0
active_workers = 0
total_throughput = 0.0
max_eta = 0
worker_details = []
for worker_id, worker in self._workers.items():
weight = worker['file_size_bytes'] / self._total_bytes if self._total_bytes > 0 else 1.0 / len(self._workers)
total_weighted_progress += worker['progress_pct'] * weight
if worker['status'] == 'processing':
active_workers += 1
total_throughput += worker['throughput_mbps']
# Defensive type checking for eta_seconds to prevent comparison errors
worker_eta = worker['eta_seconds']
if isinstance(worker_eta, (int, float)) and not isinstance(worker_eta, bool):
max_eta = max(max_eta, worker_eta)
else:
# Log the issue and reset to 0 if eta_seconds is corrupted
self.log(f"Warning: Worker {worker_id} has invalid eta_seconds type: {type(worker_eta)} = {worker_eta}", "WARNING") if hasattr(self, 'log') else None
worker['eta_seconds'] = 0
worker_details.append({
'id': worker_id,
'task_name': worker['task_name'],
'progress_pct': worker['progress_pct'],
'fps': worker['fps'],
'status': worker['status'],
'throughput_mbps': worker['throughput_mbps'],
'eta_seconds': worker['eta_seconds'],
'segment_info': worker['segment_info']
})
return {
'overall_progress': total_weighted_progress,
'active_workers': max(active_workers, self._active_thread_count),
'total_workers': max(len(self._workers), self._total_thread_count),
'throughput_mbps': total_throughput,
'eta_seconds': max_eta,
'workers': worker_details,
'total_bytes': self._total_bytes,
'processed_bytes': self._processed_bytes,
'queue_size': self._queue_size,
'total_queue_size': self._total_queue_size,
'current_file': self._current_file_index,
'total_files': self._total_files,
'actual_thread_count': self._active_thread_count
}
def set_callback(self, callback):
"""Set callback function for progress updates."""
with self._lock:
self._callback = callback
def notify_callback(self):
"""Notify the callback with current progress, respecting throttling interval."""
with self._lock:
current_time = time.time()
# Check if enough time has passed since last callback
if (self._callback and not self._notifying and
(current_time - self._last_callback_time) >= self._callback_interval):
self._notifying = True
self._last_callback_time = current_time
try:
progress_data = self.get_aggregate_progress()
self._callback(progress_data)
except Exception as e:
# Enhanced error logging with stack trace
import traceback
error_msg = f"Progress callback error: {type(e).__name__}: {str(e)}"
stack_trace = traceback.format_exc()
# Log to file or console if logger is available
if hasattr(self, 'log'):
self.log(f"{error_msg}\nStack trace:\n{stack_trace}", "ERROR")
else:
print(f"ERROR: {error_msg}\nStack trace:\n{stack_trace}")
finally:
self._notifying = False
def set_thread_pool_info(self, active_count, total_count):
"""Update thread pool worker count information."""
with self._lock:
self._active_thread_count = active_count
self._total_thread_count = total_count
def set_queue_info(self, current_size, total_size):
"""Update queue size information."""
with self._lock:
self._queue_size = current_size
self._total_queue_size = total_size
def set_file_progress_info(self, current_file, total_files):
"""Update file processing progress information."""
with self._lock:
self._current_file_index = current_file
self._total_files = total_files
def complete_worker(self, worker_id):
"""Mark a worker as completed."""
with self._lock:
if worker_id in self._workers:
self._workers[worker_id]['status'] = 'completed'
self._workers[worker_id]['progress_pct'] = 1.0
self.notify_callback()
def fail_worker(self, worker_id, error_message):
"""Mark a worker as failed."""
with self._lock:
if worker_id in self._workers:
self._workers[worker_id]['status'] = 'failed'
self._workers[worker_id]['error'] = error_message
self.notify_callback()
class VideoCompressor:
def __init__(self, config_path="config.json"):
self.config = self.load_config(config_path)
self.logger = None
self.setup_enhanced_logging()
self.processed_files = []
self.failed_files = []
self.progress_aggregator = ProgressAggregator(self.config)
def load_config(self, config_path):
"""Load configuration from JSON file."""
try:
with open(config_path, 'r') as f:
config = json.load(f)
return config
except FileNotFoundError:
print(f"Config file {config_path} not found. Creating default config...")
default_config = {
"ffmpeg_path": "/opt/homebrew/bin/ffmpeg",
"temp_dir": "/tmp/video_compression",
"log_dir": "./logs",
"compression_settings": {
"target_bitrate_reduction": 0.5,
"preserve_10bit": True,
"preserve_metadata": True,
"video_codec": "libx265",
"preset": "medium",
"crf": 23,
"enable_hardware_acceleration": True
},
"safety_settings": {
"min_free_space_gb": 15,
"verify_integrity": True,
"create_backup_hash": True,
"max_retries": 3,
"delete_original_after_compression": True
},
"large_file_settings": {
"threshold_gb": 10,
"segmentation_threshold_gb": 10,
"enhanced_monitoring": True,
"progress_update_interval": 10,
"hash_chunk_size_mb": 5,
"extended_timeouts": True,
"use_same_filesystem": True
},
"segmentation_settings": {
"segment_duration_seconds": 600,
"duration_threshold_minutes": 60,
"segmentation_timeout_minutes_per_gb": 1,
"min_segmentation_timeout_minutes": 5,
"size_difference_warning_percent": 5
},
"timeout_settings": {
"small_file_timeout_hours": 2,
"segment_timeout_hours": 1,
"merge_size_difference_warning_percent": 10,
"segment_progress_log_interval_seconds": 30
},
"logging_settings": {
"max_log_files": 5,
"max_log_size_mb": 10,
"console_level": "INFO",
"file_level": "DEBUG"
},
"parallel_processing": {
"enabled": True,
"max_workers": 4,
"segment_parallel": True
}
}
with open(config_path, 'w') as f:
json.dump(default_config, f, indent=2)
return default_config
except json.JSONDecodeError as e:
print(f"Error parsing config file: {e}")
sys.exit(1)
def setup_enhanced_logging(self):
"""Setup enhanced logging system with rotation and levels."""
log_dir = Path(self.config["log_dir"])
log_dir.mkdir(exist_ok=True)
# Clean up old log files based on config
max_logs = self.config.get("logging_settings", {}).get("max_log_files", 5)
self.cleanup_old_logs(log_dir, max_logs)
# Setup main logger
self.logger = logging.getLogger('VideoCompressor')
self.logger.setLevel(logging.DEBUG)
# Clear any existing handlers
for handler in self.logger.handlers[:]:
self.logger.removeHandler(handler)
# Create formatters
detailed_formatter = logging.Formatter(
'%(asctime)s [%(levelname)8s] %(name)s: %(message)s',
datefmt='%Y-%m-%d %H:%M:%S'
)
console_formatter = logging.Formatter(
'[%(levelname)s] %(message)s'
)
# Get configurable log levels first
console_level = getattr(logging, self.config.get("logging_settings", {}).get("console_level", "INFO"))
file_level = getattr(logging, self.config.get("logging_settings", {}).get("file_level", "DEBUG"))
# File handler with configurable rotation
max_size_mb = self.config.get("logging_settings", {}).get("max_log_size_mb", 10)
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
log_file = log_dir / f"video_compression_{timestamp}.log"
file_handler = logging.handlers.RotatingFileHandler(
log_file, maxBytes=max_size_mb*1024*1024, backupCount=3
)
file_handler.setLevel(file_level)
file_handler.setFormatter(detailed_formatter)
# Console handler
console_handler = logging.StreamHandler()
console_handler.setLevel(console_level)
console_handler.setFormatter(console_formatter)
self.logger.addHandler(file_handler)
self.logger.addHandler(console_handler)
# Log session start
self.logger.info("=== Video Compression Session Started ===")
self.logger.info(f"Timestamp: {datetime.now()}")
self.logger.debug(f"Config: {json.dumps(self.config, indent=2)}")
self.logger.info(f"Log file: {log_file}")
def cleanup_old_logs(self, log_dir, keep_count=5):
"""Clean up old log files, keeping only the most recent ones."""
try:
log_files = sorted(
[f for f in log_dir.glob("video_compression_*.log*")],
key=lambda x: x.stat().st_mtime,
reverse=True
)
# Remove files beyond keep_count
for old_log in log_files[keep_count:]:
try:
old_log.unlink()
print(f"π§Ή Cleaned up old log: {old_log.name}")
except Exception as e:
print(f"β οΈ Failed to remove old log {old_log}: {e}")
except Exception as e:
print(f"β οΈ Error during log cleanup: {e}")
def log(self, message, level="INFO"):
"""Enhanced logging with proper levels and structured output."""
if not self.logger:
print(f"[{level}] {message}")
return
level_map = {
"DEBUG": self.logger.debug,
"INFO": self.logger.info,
"WARNING": self.logger.warning,
"ERROR": self.logger.error,
"CRITICAL": self.logger.critical
}
log_func = level_map.get(level.upper(), self.logger.info)
log_func(message)
def check_disk_space(self, file_path, safety_multiplier=2.5):
"""Enhanced disk space checking with cross-filesystem support."""
try:
file_size = os.path.getsize(file_path)
file_path_obj = Path(file_path)
# Determine actual temp directory that will be used (matching compression logic)
if self.config.get("large_file_settings", {}).get("use_same_filesystem", True):
# Same filesystem temp directory (matches compression behavior)
actual_temp_dir = file_path_obj.parent / ".video_compression_temp"
self.log(f"π Using same-filesystem temp checking: {actual_temp_dir}", "DEBUG")
else:
# Configured temp directory
actual_temp_dir = Path(self.config["temp_dir"])
self.log(f"π Using configured temp directory: {actual_temp_dir}", "DEBUG")
# Ensure temp dir exists for space checking
actual_temp_dir.mkdir(exist_ok=True)
# Use psutil for more accurate disk space info
temp_usage = psutil.disk_usage(str(actual_temp_dir))
file_parent_usage = psutil.disk_usage(str(file_path_obj.parent))
temp_available_gb = temp_usage.free / (1024**3)
file_parent_available_gb = file_parent_usage.free / (1024**3)
# Required space calculation for large files
required_bytes = file_size * safety_multiplier
required_gb = required_bytes / (1024**3)
min_free_space = self.config["safety_settings"]["min_free_space_gb"]
self.log(f"πΎ Enhanced disk space analysis:", "DEBUG")
self.log(f" File size: {file_size / (1024**3):.2f}GB", "INFO")
self.log(f" Required temp space: {required_gb:.2f}GB", "INFO")
self.log(f" Actual temp dir available: {temp_available_gb:.2f}GB", "INFO")
self.log(f" File directory available: {file_parent_available_gb:.2f}GB", "DEBUG")
self.log(f" Minimum required free: {min_free_space}GB", "DEBUG")
# Check temp directory space (using actual temp location)
if temp_available_gb < (required_gb + min_free_space):
return False, f"Insufficient temp space. Need {required_gb + min_free_space:.2f}GB, have {temp_available_gb:.2f}GB"
# Check if we can write the final file
if file_parent_available_gb < (file_size / (1024**3) + min_free_space):
return False, f"Insufficient space for final file. Need {file_size / (1024**3) + min_free_space:.2f}GB, have {file_parent_available_gb:.2f}GB"
self.log(f"β
Sufficient disk space available", "INFO")
return True, "Sufficient disk space available"
except Exception as e:
self.log(f"Error checking disk space: {e}", "ERROR")
return False, f"Disk space check failed: {e}"
def calculate_file_hash(self, file_path, chunk_size=None):
"""Calculate SHA-256 hash optimized for large files."""
if chunk_size is None:
# Use config-based chunk size for large files
chunk_size_mb = self.config.get("large_file_settings", {}).get("hash_chunk_size_mb", 5)
chunk_size = chunk_size_mb * 1024 * 1024
file_size = os.path.getsize(file_path)
self.log(f"π Calculating hash for {Path(file_path).name} ({file_size / (1024**3):.2f}GB)", "INFO")
hash_sha256 = hashlib.sha256()
bytes_processed = 0
last_progress_log = 0
try:
with open(file_path, "rb") as f:
while True:
chunk = f.read(chunk_size)
if not chunk:
break
hash_sha256.update(chunk)
bytes_processed += len(chunk)
# Log progress every 10% for large files (>1GB)
if file_size > 1024**3:
progress = (bytes_processed / file_size) * 100
if progress - last_progress_log >= 10:
self.log(f" Hash progress: {progress:.1f}%", "DEBUG")
last_progress_log = progress
hash_result = hash_sha256.hexdigest()
self.log(f"β
Hash calculated: {hash_result[:16]}...", "DEBUG")
return hash_result
except Exception as e:
self.log(f"Error calculating hash: {e}", "ERROR")
return None
def get_video_info(self, file_path):
"""Get detailed video information with enhanced error handling and fallback strategies."""
file_size_gb = os.path.getsize(file_path) / (1024**3)
# Dynamic timeout based on file size and config
if self.config.get("large_file_settings", {}).get("extended_timeouts", True):
timeout = max(30, int(30 + file_size_gb * 15)) # More generous for large files
else:
timeout = 30
# Strategy 1: Standard ffprobe with full stream analysis
cmd_full = [
self.config["ffmpeg_path"].replace("ffmpeg", "ffprobe"),
"-v", "quiet",
"-print_format", "json",
"-show_format",
"-show_streams",
str(file_path)
]
self.log(f"π Analyzing video info (timeout: {timeout}s)", "DEBUG")
try:
result = subprocess.run(cmd_full, capture_output=True, text=True, timeout=timeout)
if result.returncode == 0:
video_info = json.loads(result.stdout)
self.log(f"β
Video analysis complete", "DEBUG")
return video_info
else:
self.log(f"ffprobe standard analysis failed: {result.stderr.strip()}", "WARNING")
except subprocess.TimeoutExpired:
self.log(f"ffprobe timeout after {timeout}s for large file", "WARNING")
except json.JSONDecodeError as e:
self.log(f"ffprobe returned invalid JSON: {e}", "WARNING")
except Exception as e:
self.log(f"ffprobe standard analysis error: {e}", "WARNING")
# Strategy 2: Minimal ffprobe with format-only analysis
self.log(f"π Attempting minimal ffprobe analysis...", "DEBUG")
cmd_minimal = [
self.config["ffmpeg_path"].replace("ffmpeg", "ffprobe"),
"-v", "error", # Reduce verbosity to minimize noise
"-print_format", "json",
"-show_format",
"-select_streams", "v:0", # Only first video stream
str(file_path)
]
try:
result = subprocess.run(cmd_minimal, capture_output=True, text=True, timeout=timeout)
if result.returncode == 0:
video_info = json.loads(result.stdout)
self.log(f"β
Minimal video analysis successful", "DEBUG")
return video_info
else:
self.log(f"ffprobe minimal analysis failed: {result.stderr.strip()}", "WARNING")
except subprocess.TimeoutExpired:
self.log(f"ffprobe minimal timeout after {timeout}s", "WARNING")
except json.JSONDecodeError as e:
self.log(f"ffprobe minimal returned invalid JSON: {e}", "WARNING")
except Exception as e:
self.log(f"ffprobe minimal analysis error: {e}", "WARNING")
# Strategy 3: Basic file probe with ignore errors
self.log(f"π Attempting basic file probe (ignore errors)...", "DEBUG")
cmd_basic = [
self.config["ffmpeg_path"].replace("ffmpeg", "ffprobe"),
"-v", "error",
"-print_format", "json",
"-show_format",
"-ignore_unknown", # Ignore unknown streams/codecs
str(file_path)
]
try:
result = subprocess.run(cmd_basic, capture_output=True, text=True, timeout=timeout)
if result.returncode == 0:
video_info = json.loads(result.stdout)
self.log(f"β
Basic file probe successful", "DEBUG")
return video_info
else:
self.log(f"ffprobe basic probe failed: {result.stderr.strip()}", "WARNING")
except subprocess.TimeoutExpired:
self.log(f"ffprobe basic timeout after {timeout}s", "WARNING")
except json.JSONDecodeError as e:
self.log(f"ffprobe basic returned invalid JSON: {e}", "WARNING")
except Exception as e:
self.log(f"ffprobe basic probe error: {e}", "WARNING")
# All strategies failed
self.log(f"β All ffprobe strategies failed for file: {os.path.basename(file_path)}", "ERROR")
return None
def get_video_duration(self, video_info):
"""Extract video duration in seconds from video info."""
try:
# Try to get duration from format first
format_info = video_info.get("format", {})
if "duration" in format_info:
return float(format_info["duration"])
# Fallback: get from video stream
video_streams = [s for s in video_info.get("streams", []) if s.get("codec_type") == "video"]
if video_streams and "duration" in video_streams[0]:
return float(video_streams[0]["duration"])
except (ValueError, KeyError, TypeError):
pass
return 0.0
def estimate_duration_fallback(self, file_path):
"""Estimate video duration using file size when ffprobe fails."""
try:
file_size = os.path.getsize(file_path)
file_size_mb = file_size / (1024 * 1024)
# Rough estimation based on typical bitrates for different video types
# These are conservative estimates for common video formats
typical_bitrates = {
'.mp4': 5.0, # 5 Mbps average
'.mov': 8.0, # 8 Mbps average (often higher quality)
'.avi': 6.0, # 6 Mbps average
'.mkv': 7.0, # 7 Mbps average
'.webm': 3.0, # 3 Mbps average (web optimized)
'.m4v': 5.0, # 5 Mbps average
}
file_ext = Path(file_path).suffix.lower()
estimated_bitrate_mbps = typical_bitrates.get(file_ext, 5.0) # Default 5 Mbps
# Duration = file_size_mb / (bitrate_mbps / 8) / 60 (convert to minutes)
# Bitrate in Mbps needs to be converted to MB/s by dividing by 8
estimated_duration_minutes = file_size_mb / (estimated_bitrate_mbps / 8) / 60
estimated_duration_seconds = estimated_duration_minutes * 60
self.log(f"π Duration estimation fallback:", "DEBUG")
self.log(f" File size: {file_size_mb:.1f}MB", "DEBUG")
self.log(f" Estimated bitrate: {estimated_bitrate_mbps} Mbps", "DEBUG")
self.log(f" Estimated duration: {estimated_duration_minutes:.1f} minutes", "DEBUG")
return estimated_duration_seconds
except Exception as e:
self.log(f"Duration estimation fallback failed: {e}", "WARNING")
return 0.0
def verify_file_integrity(self, file_path, original_info=None):