Add ges-multi-split.py
[experiments/gstreamer.git] / python / ges-multi-split.py
1 #!/usr/bin/env python3
2 #
3 # ges-multi-cut - generate commands to split a video file into multiple clips
4 #
5 # Copyright (C) 2016  Antonio Ospite <ao2@ao2.it>
6 #
7 # This program is free software: you can redistribute it and/or modify
8 # it under the terms of the GNU General Public License as published by
9 # the Free Software Foundation, either version 3 of the License, or
10 # (at your option) any later version.
11 #
12 # This program is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 # GNU General Public License for more details.
16 #
17 # You should have received a copy of the GNU General Public License
18 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
19
20 import os
21 import sys
22
23 CLIP_FILENAME_TEMPLATE = "sample_%s.webm"
24 CLIP_FORMAT = "video/webm:video/x-vp8:audio/x-vorbis"
25
26
27 def timeformat_to_seconds(timeformat):
28     """Convert a time string in the format HH:MM:SS.dd to seconds"""
29     multipliers = [3600, 60, 1]
30     return sum([mult*val for mult, val in
31                 zip([float(t) for t in timeformat.split(':')], multipliers)])
32
33
34 def parse_samples_list(samples_list_filename):
35     """Parse a file in a custom format.
36     Each line in the file has this format:
37
38         SAMPLE_NAME HH:MM:SS.ddd HH:MM:SS.ddd
39
40     where sample name is a string and the two time fields are the start time of the
41     sample and the end time of the sample.
42
43     Returns a list where each item is a tuple:
44         (sample_name, start_time, end_time)
45     """
46     samples = []
47
48     with open(samples_list_filename, "r") as samples_list_file:
49         for row in samples_list_file:
50             sample_name, start_timeformat, end_timeformat = row.split()
51
52             start_time = timeformat_to_seconds(start_timeformat)
53             end_time = timeformat_to_seconds(end_timeformat)
54
55             samples.append((sample_name, start_time, end_time))
56
57     return samples
58
59
60 def usage():
61     print("usage: %s <video_file> <samples_list_file>"
62           % os.path.basename(sys.argv[0]))
63
64
65 def main():
66     if len(sys.argv) < 3:
67         usage()
68         return 1
69
70     master_file = sys.argv[1]
71     samples_list_filename = sys.argv[2]
72
73     samples = parse_samples_list(samples_list_filename)
74     for sample_name, start_time, end_time in samples:
75         duration = round(end_time - start_time, 2)
76         clip_filename = CLIP_FILENAME_TEMPLATE % sample_name
77         print("ges-launch-1.0 +clip \"%s\" inpoint=%s duration=%s -o \"%s\" --format=\"%s\"" %
78               (master_file, start_time, duration, clip_filename, CLIP_FORMAT))
79
80
81 if __name__ == "__main__":
82     sys.exit(main())