-
Notifications
You must be signed in to change notification settings - Fork 0
/
media_file_util.py
57 lines (43 loc) · 1.6 KB
/
media_file_util.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import logging
import os
from typing import Optional
from base_util import run_shell_command
from io_util import get_source_id
from models import MediaFile
logger = logging.getLogger(__name__)
def validate_media_file(media_file_path: str) -> Optional[MediaFile]:
if not os.path.exists(media_file_path):
logger.error(f"Could not find media file at: {media_file_path}")
return None
duration_ms = get_media_file_length(media_file_path)
if duration_ms <= 0:
logger.error("Not a valid media file")
return None
return MediaFile(media_file_path, get_source_id(media_file_path))
# returns duration in ms
def get_media_file_length(media_file: str):
result = run_shell_command(
" ".join(
[
"ffprobe",
"-v",
"error",
"-show_entries",
"format=duration",
"-of",
"default=noprint_wrappers=1:nokey=1",
media_file,
]
),
)
return int(float(result) * 1000) # NOTE unsafe! (convert secs to ms)
def too_close_to_edge(keyframe_ms: int, duration_ms: int, window_size_ms: int):
if keyframe_ms + (window_size_ms / 2) > duration_ms or keyframe_ms < (
window_size_ms / 2
):
return True
return False
def get_start_frame(keyframe_ms: int, window_size_ms: int, sample_rate: int):
return (keyframe_ms - window_size_ms // 2) * sample_rate // 1000
def get_end_frame(keyframe_ms: int, window_size_ms: int, sample_rate: int):
return (keyframe_ms + window_size_ms // 2) * sample_rate // 1000