-
Notifications
You must be signed in to change notification settings - Fork 0
/
video_converter.py
86 lines (71 loc) · 3.05 KB
/
video_converter.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
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
#!/usr/bin/env python
""" Main module of the converter.
You can pass the configuration file as a command-line argument. """
import signal
import time
import errno
import sys
import threading
import os
import logging
from encoders import EncoderFactory
from configuration import Configuration
class Main(object):
""" The program's main execution class """
def __init__(self, config_file):
self.configuration = Configuration.read_from(
config_file, EncoderFactory.create_encoding_profile)
logging.basicConfig(
format="[%(levelname)s] %(asctime)s - %(message)s",
level=logging.getLevelName(self.configuration.loglevel))
logging.debug("Loaded configuration: %s", self.configuration)
self._interrupt = threading.Event()
self._converters = dict()
self._converters_lock = threading.Lock()
def sigterm_handler(self, signum, frame):
""" handle system signals """
logging.info("Shutting down")
self._interrupt.set()
def run(self):
""" main loop """
logging.info("Monitoring '%s'", self.configuration.input_directory)
while not self._interrupt.isSet():
try:
# remove finished threads
with self._converters_lock:
self._converters = {k: v for k, v in self._converters.items()
if v.is_alive()}
# convert new files
files = self.get_monitored_files()
with self._converters_lock:
for file in files:
if file in self._converters:
continue
self._converters[file] = EncoderFactory.create_encoder(
file, self.configuration, self._interrupt,)
self._converters[file].start()
# if interrupted between sleeps
if not self._interrupt.isSet():
time.sleep(self.configuration.poll_frequency)
except IOError as ex:
if ex.errno != errno.EINTR:
raise
logging.info("Waiting for threads to exit")
for converter in self._converters.values():
converter.join()
def get_monitored_files(self):
""" retrieve list of files in the monitored directory """
input_directory = self.configuration.input_directory
video_extensions = self.configuration.video_extensions
return [os.path.join(input_directory, f) for f in os.listdir(input_directory)
if os.path.splitext(f)[1][1:] in video_extensions]
if __name__ == "__main__":
configuration_file = os.path.join(
os.path.dirname(os.path.abspath(__file__)), "configuration.ini")
if len(sys.argv) == 2:
configuration_file = sys.argv[1]
main = Main(configuration_file)
# stop the program gracefully on interrupt and terminate
signal.signal(signal.SIGINT, main.sigterm_handler)
signal.signal(signal.SIGTERM, main.sigterm_handler)
main.run()