-
Notifications
You must be signed in to change notification settings - Fork 1
/
split-video
executable file
·228 lines (200 loc) · 7.28 KB
/
split-video
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
#!/usr/bin/env python3
# -*- python -*-
#
# Copyright 2016 by Chris Osborn <[email protected]>
#
# This file is part of viddin.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License at <http://www.gnu.org/licenses/> for
# more details.
import argparse
import os
import datetime
import re
import math
import sys
import viddin
def build_argparser():
parser = argparse.ArgumentParser()
parser.add_argument("filename", help="Video to split")
parser.add_argument("ranges", nargs="+", help="Split at offset(s) or ranges. Use negative number for offset from end. If argument is a filename, load offsets from it.")
parser.add_argument("--transcode", action="store_true", help="transcode video for perfect split points")
parser.add_argument("--transcode-flags", help="extra flags to pass to transcoder")
parser.add_argument("--iframes", action="store_true", help="compare split positions to iframes from video")
parser.add_argument("--output", help="name to use when creating splits")
parser.add_argument("--outtype", help="force split to be this type")
parser.add_argument("--quality", help="use this quality level when transcoding. Higher numbers are worse quality, default is 20")
parser.add_argument("--trimend", help="Frames to remove from end")
parser.add_argument("--chapters", action="store_true", help="Split a video by chapters")
parser.add_argument("--debug", action="store_true", help="Turn on debug output")
return parser
def findIframes(filename, output):
if not os.path.exists(output) or os.path.getctime(output) < os.path.getctime(filename):
if args.debug:
print("Finding I frames " + filename)
os.system("find-iframes \"%s\" \"%s\" > /dev/null 2>&1" % (filename, output))
def findNearest(pos, before):
prev = 0
print(pos, before)
for frame in iframes:
if pos < frame:
if before:
return prev
else:
return frame
prev = frame
def splitVideo(segrange, filename, output=None, trim=None, quality=None,
transcodeFlag=False, transcodeOptions=None, iframeFlag=False):
video = viddin.Media(filename)
base, ext = os.path.splitext(video.path)
vlen = video.length
if not segrange[1]:
segrange[1] = vlen
if not output:
output = "%sc%s" % (base, ext)
if trim:
fps = video.framesPerSecond
trim = float(trim) / fps
if os.path.exists(output):
os.remove(output)
start = segrange[0]
end = segrange[1]
if trim:
end -= trim
if transcodeFlag: # and start > 0.0:
# FIXME - match codec of source?
qstr = ""
if quality:
qstr = "-crf %s" % (quality)
# cmd = "ffmpeg -y -i \"%s\" -ss %f -to %f -c copy -vcodec libx264 -map 0 %s \"%s\"" \
# % (video.path, start, end, qstr, output)
cmd = ["rip-video", "--start-at", str(start), "--stop-at", str(end), video.path, output]
if transcodeOptions:
cmd.extend(transcodeOptions.split(" "))
print(cmd)
viddin.runCommand(cmd)
else:
if iframeFlag:
start = findNearest(start, True)
iend = findNearest(end, False)
if iend:
end = iend
if start > 0.0:
if end < vlen:
temp = "split-%i%s" % (os.getpgid(0), ext)
if os.path.exists(temp):
os.remove(temp)
else:
temp = output
cmd = ["mkvmerge", "--split", "parts:%s-%s" %
(datetime.timedelta(seconds = start), datetime.timedelta(seconds = end)),
"-o", temp, video.path]
print(cmd)
viddin.runCommand(cmd)
else:
temp = video.path
if end < vlen:
tlen = end - start
cmd = ["ffmpeg", "-y", "-i", temp, "-t", str(tlen), "-codec", "copy", "-map", "0",
output]
print(cmd)
viddin.runCommand(cmd)
if temp != video.path and temp != output:
os.remove(temp)
return output
def main():
args = build_argparser().parse_args()
segments = []
if len(args.ranges) == 1 and os.path.isfile(args.ranges[0]):
ranges = []
with open(args.ranges[0]) as f:
for line in f:
line = line.strip()
if line[0] >= '0' and line[0] <= '9':
ranges.append(line)
args.ranges = ranges
for offset in args.ranges:
if re.match("^[-+]?[0-9]+([.,][0-9]+)?$", offset) \
or re.match("^[-+]?[0-9]+(:[0-9]+)+([.,][0-9]+)?$", offset):
tc = viddin.decodeTimecode(offset)
if offset[0] != '+':
if len(segments) == 0:
segments.append([0, tc])
else:
if not segments[-1][1]:
segments[-1][1] = tc
if tc > 0:
segments.append([tc, None])
elif re.match("^[0-9]+([.,][0-9]+)?-[0-9]+([.,][0-9]+)?$", offset) \
or re.match("^[0-9]+(:[0-9]+)+([.,][0-9]+)?-[0-9]+(:[0-9]+)+([.,][0-9]+)?$", offset):
times = offset.split("-")
segments.append([viddin.decodeTimecode(times[0]), viddin.decodeTimecode(times[1])])
elif re.match("^[0-9]+([.,][0-9]+)?-$", offset) \
or re.match("^[0-9]+(:[0-9]+)+([.,][0-9]+)?-?$", offset):
times = offset.split("-")
segments.append([viddin.decodeTimecode(times[0]), None])
else:
print("Unrecognized timecode " + offset)
sys.exit(1)
if args.chapters:
vfile = viddin.VideoSpec(args.filename)
vfile.normalizeChapters()
chapters = vfile.chapters
segments = []
for beg, end in zip(chapters, chapters[1:]):
segments.append([beg.position, end.position])
if len(segments) < 1:
print("Nothing to do")
return
append = ""
digits = int(math.floor(math.log(len(segments), 10)) + 1)
append = "_%%0%ii" % digits
video, ext = os.path.splitext(args.filename)
if args.output:
ovid, oext = os.path.splitext(args.output)
append = ""
else:
ovid = video
oext = ext
ifile = video + ".iframes"
#if not args.iframes and os.path.exists(ifile) \
# and os.path.getctime(ifile) >= os.path.getctime(args.filename):
# args.iframes = True
if args.iframes:
findIframes(args.filename, ifile)
iframes = []
with open(ifile) as f:
for line in f:
iframes.append(float(line))
# FIXME - if transcoding and more than one segment do the entire thing
# and force frames? If only one segment then skip mkvmerge and
# let ffmpeg pull the segment
outtype = args.outtype
if not outtype:
outtype = oext
if not args.transcode:
outtype = ext
if outtype[0] != '.':
outtype = "." + outtype
if outtype == ".avi":
outtype = ".mkv"
for segrange in segments:
output = ovid + append + outtype
if len(append):
output = output % (segments.index(segrange) + 1)
splitVideo(segrange, args.filename, output, args.trimend, quality=args.quality,
transcodeFlag=args.transcode, transcodeOptions=args.transcode_flags,
iframeFlag=args.iframes)
# FIXME - if transcoding force keyframes into the right spot, but
# re-read because ffmpeg isn't exact and puts them "close"
return
if __name__ == '__main__':
exit(main() or 0)