forked from funnyzak/ffmpeg-service
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
1820 lines (1536 loc) · 66.6 KB
/
app.py
File metadata and controls
1820 lines (1536 loc) · 66.6 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
# -*- coding: utf-8 -*-
# @Time : 2025/7/31 10:00
# @Github : https://github.com/funnyzak
# @File : app.py
# @Description:FFmpeg Video Processing Service
"""
FFmpeg Video Processing Service
A Flask-based microservice for video processing using FFmpeg
"""
import os
import json
import uuid
import subprocess
import time
import threading
import logging
import logging.handlers
from urllib.parse import urlparse
import requests
from flask import Flask, request, jsonify, send_file
import magic
from functools import wraps
# Configure logging
def setup_logging():
"""Setup comprehensive logging configuration"""
# Create logs directory if it doesn't exist
log_dir = os.getenv("LOG_DIR", "./logs")
os.makedirs(log_dir, exist_ok=True)
# Get log level from environment
log_level_str = os.getenv("LOG_LEVEL", "INFO").upper()
log_level = getattr(logging, log_level_str, logging.INFO)
# Configure root logger
root_logger = logging.getLogger()
root_logger.setLevel(log_level)
# Clear existing handlers
for handler in root_logger.handlers[:]:
root_logger.removeHandler(handler)
# Create formatters
detailed_formatter = logging.Formatter(
'%(asctime)s [%(levelname)s] [%(name)s:%(lineno)d] '
'[%(funcName)s] [%(threadName)s] - %(message)s',
datefmt='%Y-%m-%d %H:%M:%S'
)
simple_formatter = logging.Formatter(
'%(asctime)s [%(levelname)s] %(name)s - %(message)s',
datefmt='%Y-%m-%d %H:%M:%S'
)
# Console handler
console_handler = logging.StreamHandler()
console_handler.setLevel(log_level)
console_handler.setFormatter(simple_formatter)
root_logger.addHandler(console_handler)
# File handler for all logs
all_log_file = os.path.join(log_dir, "all.log")
file_handler = logging.handlers.RotatingFileHandler(
all_log_file, maxBytes=10*1024*1024, backupCount=5
)
file_handler.setLevel(log_level)
file_handler.setFormatter(detailed_formatter)
root_logger.addHandler(file_handler)
# Suppress Flask and Werkzeug logs in production
debug_mode = os.getenv("FLASK_DEBUG", "false").lower()
if debug_mode not in ("true", "1", "yes", "on"):
logging.getLogger("werkzeug").setLevel(logging.WARNING)
logging.getLogger("gunicorn").setLevel(logging.WARNING)
return root_logger
# Initialize logging
logger = setup_logging()
app = Flask(__name__)
# Configuration from environment variables
TEMP_DIR = os.getenv("TEMP_DIR", "/tmp/videos")
MAX_FILE_SIZE = int(os.getenv("MAX_FILE_SIZE", "524288000")) # Default: 500MB
FILE_RETENTION_HOURS = int(os.getenv("FILE_RETENTION_HOURS", "2"))
CLEANUP_INTERVAL_MINUTES = int(os.getenv("CLEANUP_INTERVAL_MINUTES", "30"))
# Parse allowed extensions from environment
allowed_ext_str = os.getenv(
"ALLOWED_VIDEO_EXTENSIONS", "mp4,avi,mov,mkv,flv,wmv,webm,m4v"
)
ALLOWED_VIDEO_EXTENSIONS = {
f".{ext.strip()}" for ext in allowed_ext_str.split(",")
}
# Parse allowed audio extensions from environment
allowed_audio_ext_str = os.getenv(
"ALLOWED_AUDIO_EXTENSIONS", "mp3,wav,flac,aac,ogg,m4a,wma,opus"
)
ALLOWED_AUDIO_EXTENSIONS = {
f".{ext.strip()}" for ext in allowed_audio_ext_str.split(",")
}
# Parse supported video output formats from environment
video_output_fmt_str = os.getenv(
"SUPPORTED_VIDEO_OUTPUT_FORMATS", "mp4,avi,mov,mkv,webm"
)
SUPPORTED_VIDEO_OUTPUT_FORMATS = {
fmt.strip() for fmt in video_output_fmt_str.split(",")
}
# Parse supported audio output formats from environment
audio_output_fmt_str = os.getenv(
"SUPPORTED_AUDIO_OUTPUT_FORMATS", "mp3,wav,flac,aac,ogg,m4a,opus"
)
SUPPORTED_AUDIO_OUTPUT_FORMATS = {
fmt.strip() for fmt in audio_output_fmt_str.split(",")
}
# API Key authentication configuration
API_KEYS_STR = os.getenv("API_KEYS", "")
API_KEYS = (
{key.strip() for key in API_KEYS_STR.split(",") if key.strip()}
if API_KEYS_STR
else set()
)
# Base URL configuration for full path URLs
BASE_URL = os.getenv("BASE_URL", "").rstrip("/") # Remove trailing slash
def log_startup_info():
"""Log startup information"""
logger.info("=" * 60)
logger.info("FFmpeg Service Starting")
logger.info("=" * 60)
logger.info(f"Python version: {os.sys.version}")
logger.info(f"Working directory: {os.getcwd()}")
logger.info(f"Log level: {os.getenv('LOG_LEVEL', 'INFO')}")
logger.info(f"Log directory: {os.getenv('LOG_DIR', './logs')}")
logger.info(f"Flask debug mode: {os.getenv('FLASK_DEBUG', 'false')}")
logger.info(f"Gunicorn workers: {os.getenv('GUNICORN_WORKERS', '4')}")
logger.info(f"Gunicorn worker class: {os.getenv('GUNICORN_WORKER_CLASS', 'sync')}")
logger.info(f"Gunicorn timeout: {os.getenv('GUNICORN_TIMEOUT', '120')}s")
logger.info(f"Gunicorn max requests: {os.getenv('GUNICORN_MAX_REQUESTS', '1000')}")
max_requests_jitter = os.getenv('GUNICORN_MAX_REQUESTS_JITTER', '100')
logger.info(f"Gunicorn max requests jitter: {max_requests_jitter}")
gunicorn_bind = os.getenv('GUNICORN_BIND', '0.0.0.0:8080')
logger.info(f"Gunicorn bind: {gunicorn_bind}")
gunicorn_workers = os.getenv('GUNICORN_WORKERS', '4')
logger.info(f"Gunicorn workers: {gunicorn_workers}")
# Log configuration
logger.info("Configuration loaded:")
logger.info(f" TEMP_DIR: {TEMP_DIR}")
max_file_size_mb = MAX_FILE_SIZE / 1024 / 1024
logger.info(f" MAX_FILE_SIZE: {MAX_FILE_SIZE} bytes ({max_file_size_mb:.1f} MB)")
logger.info(f" FILE_RETENTION_HOURS: {FILE_RETENTION_HOURS}")
logger.info(f" CLEANUP_INTERVAL_MINUTES: {CLEANUP_INTERVAL_MINUTES}")
logger.info(f" ALLOWED_VIDEO_EXTENSIONS: {ALLOWED_VIDEO_EXTENSIONS}")
logger.info(f" ALLOWED_AUDIO_EXTENSIONS: {ALLOWED_AUDIO_EXTENSIONS}")
logger.info(f" SUPPORTED_VIDEO_OUTPUT_FORMATS: {SUPPORTED_VIDEO_OUTPUT_FORMATS}")
logger.info(f" SUPPORTED_AUDIO_OUTPUT_FORMATS: {SUPPORTED_AUDIO_OUTPUT_FORMATS}")
api_keys_configured = len(API_KEYS) > 0
logger.info(f" API_KEYS configured: {api_keys_configured}")
base_url_status = BASE_URL or 'Not set'
logger.info(f" BASE_URL: {base_url_status}")
log_startup_info()
def log_request_info(request_id=None):
"""Log request information with optional request ID"""
if request_id is None:
request_id = str(uuid.uuid4())[:8]
log_data = {
"request_id": request_id,
"method": request.method,
"path": request.path,
"remote_addr": request.remote_addr,
"user_agent": request.headers.get("User-Agent", "Unknown"),
"content_length": request.content_length,
"content_type": request.content_type,
"headers": dict(request.headers),
"args": request.args.to_dict(),
"form": request.form.to_dict(),
"json": request.get_json(silent=True) if request.is_json else None,
}
logger.info(f"Request {request_id}: {log_data}")
return request_id
def log_response_info(request_id, status_code, response_time=None, response_data=None):
"""Log response information"""
log_data = {
"request_id": request_id,
"status_code": status_code,
"response_time_ms": response_time,
"response_data": response_data if response_data is not None else {},
}
if response_time:
logger.info(f"Response {request_id}: {log_data}")
else:
logger.info(f"Response {request_id}: {log_data}")
def log_error(request_id, error, context=None):
"""Log error with context"""
error_data = {
"request_id": request_id,
"error_type": type(error).__name__,
"error_message": str(error),
"context": context or {},
}
logger.error(f"Error {request_id}: {error_data}", exc_info=True)
def require_api_key(f):
"""Decorator to require API key authentication"""
@wraps(f)
def decorated_function(*args, **kwargs):
# Skip authentication if no API keys are configured
if not API_KEYS:
logger.debug("API key authentication disabled")
return f(*args, **kwargs)
# Get API key from request header
api_key = request.headers.get("X-API-Key")
if not api_key:
logger.warning("API key required but not provided")
return create_response(code=401, msg="API key required"), 401
if api_key not in API_KEYS:
logger.warning("Invalid API key provided")
return create_response(code=403, msg="Invalid API key"), 403
logger.debug("API key authentication successful")
return f(*args, **kwargs)
return decorated_function
class AudioProcessor:
"""Audio processing utility class"""
def __init__(self, audio_path):
self.audio_path = audio_path
self.audio_info = None
logger.debug(f"AudioProcessor initialized for: {audio_path}")
def get_audio_info(self):
"""Extract audio metadata using ffprobe"""
try:
logger.info(f"Extracting audio info from: {self.audio_path}")
cmd = [
"ffprobe",
"-v",
"quiet",
"-print_format",
"json",
"-show_format",
"-show_streams",
self.audio_path,
]
logger.debug(f"Running ffprobe command: {' '.join(cmd)}")
result = subprocess.run(
cmd, capture_output=True, text=True, check=True
)
data = json.loads(result.stdout)
# Find audio stream
audio_stream = None
for stream in data.get("streams", []):
if stream.get("codec_type") == "audio":
audio_stream = stream
break
if not audio_stream:
logger.error(f"No audio stream found in: {self.audio_path}")
raise ValueError("No audio stream found")
format_info = data.get("format", {})
self.audio_info = {
"duration": float(format_info.get("duration", 0)),
"size": int(format_info.get("size", 0)),
"format_name": format_info.get("format_name", ""),
"codec_name": audio_stream.get("codec_name", ""),
"sample_rate": int(audio_stream.get("sample_rate", 0)),
"channels": int(audio_stream.get("channels", 0)),
"bit_rate": int(format_info.get("bit_rate", 0)),
"channel_layout": audio_stream.get("channel_layout", ""),
}
logger.info(f"Audio info extracted successfully: {self.audio_info}")
return self.audio_info
except subprocess.CalledProcessError as e:
logger.error(f"FFprobe failed for {self.audio_path}: {e.stderr}")
raise Exception(f"FFprobe failed: {e.stderr}")
except json.JSONDecodeError:
logger.error(f"Failed to parse audio metadata for: {self.audio_path}")
raise Exception("Failed to parse audio metadata")
except Exception as e:
logger.error(f"Error getting audio info for {self.audio_path}: {str(e)}")
raise Exception(f"Error getting audio info: {str(e)}")
def convert_format(self, output_format, quality="medium"):
"""Convert audio to specified format"""
try:
logger.info(f"Converting audio to {output_format} format with {quality} quality")
if output_format not in SUPPORTED_AUDIO_OUTPUT_FORMATS:
logger.error(f"Unsupported audio output format: {output_format}")
raise ValueError(
f"Unsupported output format. Supported: "
f"{SUPPORTED_AUDIO_OUTPUT_FORMATS}"
)
output_filename = (
f"converted_audio_{uuid.uuid4().hex}.{output_format}"
)
output_path = os.path.join(TEMP_DIR, output_filename)
# Quality settings for different formats
quality_settings = {
"mp3": {
"low": ["-b:a", "128k"],
"medium": ["-b:a", "192k"],
"high": ["-b:a", "320k"],
},
"aac": {
"low": ["-b:a", "128k"],
"medium": ["-b:a", "192k"],
"high": ["-b:a", "256k"],
},
"ogg": {
"low": ["-q:a", "3"],
"medium": ["-q:a", "6"],
"high": ["-q:a", "9"],
},
"opus": {
"low": ["-b:a", "96k"],
"medium": ["-b:a", "128k"],
"high": ["-b:a", "192k"],
},
}
# Base command
cmd = ["ffmpeg", "-i", self.audio_path]
# Add quality settings if available for the format
if output_format in quality_settings:
settings = quality_settings[output_format]
cmd.extend(settings.get(quality, settings["medium"]))
else:
# Default settings for other formats
cmd.extend(["-b:a", "192k"])
# Add output path
cmd.extend(["-y", output_path])
logger.debug(f"Running ffmpeg command: {' '.join(cmd)}")
result = subprocess.run(cmd, capture_output=True, text=True)
if result.returncode != 0:
logger.error(f"Audio conversion failed: {result.stderr}")
raise Exception(f"Conversion failed: {result.stderr}")
# Get output file info
file_size = os.path.getsize(output_path)
logger.info(f"Audio conversion completed: {output_filename} ({file_size} bytes)")
return {
"filename": output_filename,
"file_path": output_path,
"file_size": file_size,
"format": output_format,
"url": create_download_url(output_filename),
}
except Exception as e:
logger.error(f"Audio format conversion failed for {self.audio_path}: {str(e)}")
raise Exception(f"Audio format conversion failed: {str(e)}")
def remove_leading_silence(self, threshold="-50dB", min_duration=0.1):
"""Remove silence from the beginning of audio file until sound begins
Args:
threshold: dB threshold for silence detection (default: "-50dB")
min_duration: Minimum duration in seconds to consider as silence (default: 0.1)
Returns:
dict with filename, file_path, file_size, format, and url of the processed audio
"""
try:
logger.info(f"Removing leading silence from audio: threshold={threshold}, "
f"min_duration={min_duration}")
# Validate threshold format (should be like "-50dB", "-40dB")
if not threshold.endswith("dB"):
logger.error(f"Invalid threshold format: {threshold}")
raise ValueError(
f"Invalid threshold format: {threshold}. Must be in dB format "
f"(e.g., '-50dB', '-40dB')"
)
# Validate the numeric part of threshold
try:
numeric_part = threshold[:-2] # Remove "dB" suffix
float(numeric_part) # Try to parse as number
except ValueError:
logger.error(f"Invalid threshold numeric value: {threshold}")
raise ValueError(
f"Invalid threshold: {threshold}. The numeric part must be a valid number "
f"(e.g., '-50dB', '-40dB')"
)
# Validate min_duration (must be non-negative)
if min_duration < 0:
logger.error(f"Invalid min_duration: {min_duration}")
raise ValueError(
f"Invalid min_duration: {min_duration}. Must be a non-negative number"
)
# Get the original format from the file extension
original_format = os.path.splitext(self.audio_path)[1][1:]
output_filename = f"silence_removed_{uuid.uuid4().hex}.{original_format}"
output_path = os.path.join(TEMP_DIR, output_filename)
# Build FFmpeg command with silenceremove filter
cmd = [
"ffmpeg",
"-i", self.audio_path,
"-af", f"silenceremove=start_periods=1:start_duration={min_duration}:"
f"start_threshold={threshold}:detection=peak",
"-y",
output_path
]
logger.debug(f"Running ffmpeg command: {' '.join(cmd)}")
result = subprocess.run(cmd, capture_output=True, text=True)
if result.returncode != 0:
logger.error(f"Silence removal failed: {result.stderr}")
raise Exception(f"Silence removal failed: {result.stderr}")
# Get output file info
file_size = os.path.getsize(output_path)
logger.info(f"Silence removal completed: {output_filename} ({file_size} bytes)")
return {
"filename": output_filename,
"file_path": output_path,
"file_size": file_size,
"format": original_format,
"url": create_download_url(output_filename),
}
except Exception as e:
logger.error(f"Leading silence removal failed for {self.audio_path}: {str(e)}")
raise Exception(f"Leading silence removal failed: {str(e)}")
class VideoProcessor:
"""Video processing utility class"""
def __init__(self, video_path):
self.video_path = video_path
self.video_info = None
logger.debug(f"VideoProcessor initialized for: {video_path}")
def get_video_info(self):
"""Extract video metadata using ffprobe"""
try:
logger.info(f"Extracting video info from: {self.video_path}")
cmd = [
"ffprobe",
"-v",
"quiet",
"-print_format",
"json",
"-show_format",
"-show_streams",
self.video_path,
]
logger.debug(f"Running ffprobe command: {' '.join(cmd)}")
result = subprocess.run(
cmd, capture_output=True, text=True, check=True
)
data = json.loads(result.stdout)
# Find video stream
video_stream = None
for stream in data.get("streams", []):
if stream.get("codec_type") == "video":
video_stream = stream
break
if not video_stream:
logger.error(f"No video stream found in: {self.video_path}")
raise ValueError("No video stream found")
format_info = data.get("format", {})
# Calculate frame rate safely
frame_rate_str = video_stream.get("r_frame_rate", "0/1")
if "/" in str(frame_rate_str):
try:
# Safely parse fraction format like "30/1" or "30000/1001"
numerator, denominator = frame_rate_str.split("/")
numerator = float(numerator)
denominator = float(denominator)
if denominator != 0:
frame_rate = numerator / denominator
else:
frame_rate = 0
except (ValueError, ZeroDivisionError):
frame_rate = 0
else:
try:
frame_rate = float(frame_rate_str)
except (ValueError, TypeError):
frame_rate = 0
self.video_info = {
"duration": float(format_info.get("duration", 0)),
"size": int(format_info.get("size", 0)),
"format_name": format_info.get("format_name", ""),
"codec_name": video_stream.get("codec_name", ""),
"width": int(video_stream.get("width", 0)),
"height": int(video_stream.get("height", 0)),
"frame_rate": frame_rate,
"bit_rate": int(format_info.get("bit_rate", 0)),
}
logger.info(f"Video info extracted successfully: {self.video_info}")
return self.video_info
except subprocess.CalledProcessError as e:
logger.error(f"FFprobe failed for {self.video_path}: {e.stderr}")
raise Exception(f"FFprobe failed: {e.stderr}")
except json.JSONDecodeError:
logger.error(f"Failed to parse video metadata for: {self.video_path}")
raise Exception("Failed to parse video metadata")
except Exception as e:
logger.error(f"Error getting video info for {self.video_path}: {str(e)}")
raise Exception(f"Error getting video info: {str(e)}")
def take_screenshots(self, timestamps=None, count=None):
"""Take screenshots from video"""
try:
logger.info(f"Taking screenshots from video: {self.video_path}")
if not self.video_info:
self.get_video_info()
duration = self.video_info["duration"]
screenshots = []
if timestamps:
logger.info(f"Taking screenshots at specified timestamps: {timestamps}")
# Use provided timestamps
for timestamp in timestamps:
if timestamp > duration:
logger.warning(f"Timestamp {timestamp}s exceeds video duration {duration}s")
continue
screenshots.append(self._capture_screenshot(timestamp))
elif count:
logger.info(f"Taking {count} screenshots at evenly spaced intervals")
# Take screenshots at evenly spaced intervals
if count <= 0:
raise ValueError("Screenshot count must be positive")
interval = duration / (count + 1)
for i in range(1, count + 1):
timestamp = i * interval
screenshots.append(self._capture_screenshot(timestamp))
else:
logger.info("Taking 3 default screenshots at 25%, 50%, 75% of video")
# Default: take 3 screenshots
for i in [0.25, 0.5, 0.75]:
timestamp = duration * i
screenshots.append(self._capture_screenshot(timestamp))
logger.info(f"Screenshot capture completed: {len(screenshots)} screenshots taken")
return screenshots
except Exception as e:
logger.error(f"Screenshot capture failed for {self.video_path}: {str(e)}")
raise Exception(f"Screenshot capture failed: {str(e)}")
def _capture_screenshot(self, timestamp):
"""Capture a single screenshot at specified timestamp"""
output_filename = f"screenshot_{uuid.uuid4().hex}_{int(timestamp)}.jpg"
output_path = os.path.join(TEMP_DIR, output_filename)
logger.debug(f"Capturing screenshot at {timestamp}s: {output_filename}")
cmd = [
"ffmpeg",
"-i",
self.video_path,
"-ss",
str(timestamp),
"-vframes",
"1",
"-q:v",
"2",
"-y",
output_path,
]
logger.debug(f"Running ffmpeg screenshot command: {' '.join(cmd)}")
result = subprocess.run(cmd, capture_output=True, text=True)
if result.returncode != 0:
logger.error(f"Screenshot failed at {timestamp}s: {result.stderr}")
raise Exception(f"Screenshot failed: {result.stderr}")
# Get file size
file_size = os.path.getsize(output_path)
logger.debug(f"Screenshot captured successfully: {output_filename} ({file_size} bytes)")
return {
"timestamp": timestamp,
"filename": output_filename,
"file_path": output_path,
"file_size": file_size,
"url": create_download_url(output_filename),
}
def convert_format(self, output_format, quality="medium", resolution=None):
"""Convert video to specified format with optional resolution"""
try:
logger.info(f"Converting video to {output_format} format with {quality} quality")
if resolution:
logger.info(f"Resolution scaling: {resolution}")
if output_format not in SUPPORTED_VIDEO_OUTPUT_FORMATS:
logger.error(f"Unsupported video output format: {output_format}")
raise ValueError(
f"Unsupported output format. Supported: "
f"{SUPPORTED_VIDEO_OUTPUT_FORMATS}"
)
output_filename = f"converted_{uuid.uuid4().hex}.{output_format}"
output_path = os.path.join(TEMP_DIR, output_filename)
# Quality settings
quality_settings = {
"low": ["-crf", "28"],
"medium": ["-crf", "23"],
"high": ["-crf", "18"],
}
cmd = [
"ffmpeg",
"-i",
self.video_path,
"-c:v",
"libx264",
"-c:a",
"aac",
*quality_settings.get(quality, quality_settings["medium"]),
]
# Add resolution scaling if specified
if resolution:
resolution_str = self._parse_resolution(resolution)
cmd.extend(["-vf", f"scale={resolution_str}"])
cmd.extend(["-y", output_path])
logger.debug(f"Running ffmpeg conversion command: {' '.join(cmd)}")
result = subprocess.run(cmd, capture_output=True, text=True)
if result.returncode != 0:
logger.error(f"Video conversion failed: {result.stderr}")
raise Exception(f"Conversion failed: {result.stderr}")
# Get output file info
file_size = os.path.getsize(output_path)
logger.info(f"Video conversion completed: {output_filename} ({file_size} bytes)")
return {
"filename": output_filename,
"file_path": output_path,
"file_size": file_size,
"format": output_format,
"resolution": resolution if resolution else "original",
"url": create_download_url(output_filename),
}
except Exception as e:
logger.error(f"Video format conversion failed for {self.video_path}: {str(e)}")
raise Exception(f"Format conversion failed: {str(e)}")
def extract_audio(self, output_format, quality="medium"):
"""Extract audio from video file"""
try:
logger.info(f"Extracting audio from video to {output_format} format with {quality} quality")
if output_format not in SUPPORTED_AUDIO_OUTPUT_FORMATS:
logger.error(f"Unsupported audio output format: {output_format}")
raise ValueError(
f"Unsupported audio output format. Supported: "
f"{SUPPORTED_AUDIO_OUTPUT_FORMATS}"
)
output_filename = f"extracted_audio_{uuid.uuid4().hex}.{output_format}"
output_path = os.path.join(TEMP_DIR, output_filename)
# Quality settings for different audio formats
quality_settings = {
"mp3": {
"low": ["-b:a", "128k"],
"medium": ["-b:a", "192k"],
"high": ["-b:a", "320k"],
},
"aac": {
"low": ["-b:a", "128k"],
"medium": ["-b:a", "192k"],
"high": ["-b:a", "256k"],
},
"ogg": {
"low": ["-q:a", "3"],
"medium": ["-q:a", "6"],
"high": ["-q:a", "9"],
},
"opus": {
"low": ["-b:a", "96k"],
"medium": ["-b:a", "128k"],
"high": ["-b:a", "192k"],
},
}
# Base command for audio extraction
cmd = [
"ffmpeg",
"-i", self.video_path,
"-vn", # No video
]
# Set appropriate codec for each format
if output_format == "mp3":
cmd.extend(["-acodec", "libmp3lame"])
elif output_format == "aac":
cmd.extend(["-acodec", "aac"])
elif output_format == "ogg":
cmd.extend(["-acodec", "libvorbis"])
elif output_format == "opus":
cmd.extend(["-acodec", "libopus"])
elif output_format == "flac":
cmd.extend(["-acodec", "flac"])
elif output_format == "wav":
cmd.extend(["-acodec", "pcm_s16le"])
elif output_format == "m4a":
cmd.extend(["-acodec", "aac"])
else:
# Default to MP3
cmd.extend(["-acodec", "libmp3lame"])
# Add quality settings if available for the format
if output_format in quality_settings:
settings = quality_settings[output_format]
cmd.extend(settings.get(quality, settings["medium"]))
else:
# Default settings for other formats
cmd.extend(["-b:a", "192k"])
# Add output path
cmd.extend(["-y", output_path])
logger.debug(f"Running ffmpeg audio extraction command: {' '.join(cmd)}")
result = subprocess.run(cmd, capture_output=True, text=True)
if result.returncode != 0:
logger.error(f"Audio extraction failed: {result.stderr}")
raise Exception(f"Audio extraction failed: {result.stderr}")
# Get output file info
file_size = os.path.getsize(output_path)
logger.info(f"Audio extraction completed: {output_filename} ({file_size} bytes)")
return {
"filename": output_filename,
"file_path": output_path,
"file_size": file_size,
"format": output_format,
"url": create_download_url(output_filename),
}
except Exception as e:
logger.error(f"Audio extraction failed for {self.video_path}: {str(e)}")
raise Exception(f"Audio extraction failed: {str(e)}")
def _parse_resolution(self, resolution):
"""Parse and validate resolution parameter"""
if not resolution:
return None
# Handle common resolution presets
resolution_presets = {
"240p": "426:240",
"360p": "640:360",
"480p": "854:480",
"720p": "1280:720",
"1080p": "1920:1080",
"1440p": "2560:1440",
"2160p": "3840:2160", # 4K
"4k": "3840:2160",
}
resolution_lower = str(resolution).lower()
if resolution_lower in resolution_presets:
return resolution_presets[resolution_lower]
# Handle custom resolution formats
resolution_str = str(resolution)
# Format: WIDTHxHEIGHT (e.g., "1920x1080")
if 'x' in resolution_str:
parts = resolution_str.split('x')
if len(parts) == 2:
try:
width = int(parts[0])
height = int(parts[1])
if (width > 0 and height > 0 and
width <= 7680 and height <= 4320):
return f"{width}:{height}"
except ValueError:
pass
# Format: WIDTH:HEIGHT (e.g., "1920:1080")
if ':' in resolution_str:
parts = resolution_str.split(':')
if len(parts) == 2:
try:
width = int(parts[0])
height = int(parts[1])
if (width > 0 and height > 0 and
width <= 7680 and height <= 4320):
return f"{width}:{height}"
except ValueError:
pass
# Handle single dimension with aspect ratio preservation
try:
dimension = int(resolution_str)
if dimension > 0 and dimension <= 4320:
# Assume it's height, preserve aspect ratio
return f"-1:{dimension}"
except ValueError:
pass
raise ValueError(
f"Invalid resolution format: {resolution}. "
f"Supported formats: '720p', '1080p', '1920x1080', "
f"'1280:720', or single dimension"
)
def download_media_from_url(url):
"""Download media file (video or audio) from URL"""
try:
logger.info(f"Downloading media from URL: {url}")
# Validate URL
parsed_url = urlparse(url)
if not parsed_url.scheme or not parsed_url.netloc:
logger.error(f"Invalid URL format: {url}")
raise ValueError("Invalid URL")
# Create temporary file
temp_filename = f"input_{uuid.uuid4().hex}"
temp_path = os.path.join(TEMP_DIR, temp_filename)
logger.debug(f"Created temp file: {temp_path}")
# Download file
logger.debug(f"Starting download from: {url}")
response = requests.get(url, stream=True, timeout=30)
response.raise_for_status()
# Check content type
content_type = response.headers.get("content-type", "").lower()
media_types = ["video", "audio", "application/octet-stream"]
if not any(media_type in content_type for media_type in media_types):
logger.warning(f"Content type '{content_type}' may not be a media file")
# Don't raise error, let it continue as some servers don't set correct content-type
# Check file size
content_length = response.headers.get("content-length")
if content_length:
file_size = int(content_length)
logger.info(f"Expected file size: {file_size} bytes ({file_size/1024/1024:.1f} MB)")
if file_size > MAX_FILE_SIZE:
logger.error(f"File too large: {file_size} bytes > {MAX_FILE_SIZE} bytes")
raise ValueError("File too large")
# Save file
logger.debug("Starting file download...")
with open(temp_path, "wb") as f:
downloaded = 0
for chunk in response.iter_content(chunk_size=8192):
if chunk:
f.write(chunk)
downloaded += len(chunk)
if downloaded > MAX_FILE_SIZE:
os.remove(temp_path)
logger.error(f"Downloaded file too large: {downloaded} bytes")
raise ValueError("File too large")
logger.info(f"Download completed: {temp_path} ({downloaded} bytes)")
return temp_path
except requests.exceptions.RequestException as e:
logger.error(f"Request failed for URL {url}: {str(e)}")
raise Exception(f"Failed to download media: {str(e)}")
except Exception as e:
if "temp_path" in locals() and os.path.exists(temp_path):
os.remove(temp_path)
logger.debug(f"Cleaned up temp file: {temp_path}")
logger.error(f"Download error for URL {url}: {str(e)}")
raise Exception(f"Download error: {str(e)}")
def detect_media_type(file_path):
"""Detect if file is video or audio"""
try:
# Get file extension
file_ext = os.path.splitext(file_path)[1].lower()
if file_ext in ALLOWED_VIDEO_EXTENSIONS:
return "video"
elif file_ext in ALLOWED_AUDIO_EXTENSIONS:
return "audio"
# Use magic to detect MIME type
mime_type = magic.from_file(file_path, mime=True)
if mime_type.startswith("video/"):
return "video"
elif mime_type.startswith("audio/"):
return "audio"
return "unknown"
except Exception:
return "unknown"
def create_media_processor(file_path):
"""Create appropriate processor based on media type"""
media_type = detect_media_type(file_path)
if media_type == "video":
return VideoProcessor(file_path), "video"
elif media_type == "audio":
return AudioProcessor(file_path), "audio"
else:
raise ValueError("Unsupported media type")
def save_uploaded_file(file):
"""Save uploaded file"""
try:
logger.info(f"Saving uploaded file: {file.filename}")
# Check file size
file.seek(0, 2) # Seek to end
file_size = file.tell()
file.seek(0) # Seek back to beginning
logger.info(f"Uploaded file size: {file_size} bytes ({file_size/1024/1024:.1f} MB)")
if file_size > MAX_FILE_SIZE:
logger.error(f"Uploaded file too large: {file_size} bytes > {MAX_FILE_SIZE} bytes")
raise ValueError("File too large")
# Check file extension
filename = file.filename or ""
file_ext = os.path.splitext(filename)[1].lower()
logger.debug(f"File extension: {file_ext}")
# Check if it's a supported video or audio file
if (file_ext not in ALLOWED_VIDEO_EXTENSIONS and
file_ext not in ALLOWED_AUDIO_EXTENSIONS):
logger.warning(f"Unsupported file extension: {file_ext}")
# Try to detect file type using magic
file_content = file.read(1024)
file.seek(0)
mime_type = magic.from_buffer(file_content, mime=True)
logger.debug(f"Detected MIME type: {mime_type}")
if not (mime_type.startswith("video/") or
mime_type.startswith("audio/")):
logger.error(f"Invalid file type: {mime_type}")
raise ValueError("Not a valid video or audio file")