-
Notifications
You must be signed in to change notification settings - Fork 3
/
mp4_cut.py
162 lines (145 loc) · 5.8 KB
/
mp4_cut.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
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
from datetime import datetime, timedelta
from subprocess import PIPE, call, Popen
import tempfile, os, argparse, sys, re
def get_file_duration(infilename):
'''
:param infilename: input mp4 filename
:type infilename: str
:returns: (h,m,s) tuple
'''
cmd=['ffmpeg','-i',infilename]
p=Popen(cmd,stdout=PIPE,stderr=PIPE)
output=p.stderr.read().decode('utf8')
match=re.search('Duration: (.*?)\.',output)
assert match
h,m,s= parse_ts(match.group(1))
return datetime(2017,1,1,h,m,s)
def parse_ts(instring):
'''
parse time notation
'''
x=instring.split(':')
if len(x)==2:
x.insert(0,'0')
h,m,s = map(int,x)
return (h,m,s)
def format_ts(instring):
h,m,s=parse_ts(instring)
return '%02d:%02d:%02d'%(h,m,s)
def run_cmd_dt(start,end,infname,outfname):
assert isinstance(start,datetime)
assert isinstance(end,datetime)
start_time='%02d:%02d:%02d'%(start.hour,start.minute,start.second)
end_time='%02d:%02d:%02d'%(end.hour,end.minute,end.second)
run_cmd(start_time,end_time,infname,outfname)
def run_cmd(start='00:00:00',end='23:00:00',infname='foo.mp4',outfname='outfoo.mp4'):
'''
trigger call to `ffmpeg`
'''
duration = get_duration(start,end)
cmd=['ffmpeg','-ss',format_ts(start),'-t',duration,'-i',
infname,'-acodec','copy','-vcodec','copy',
outfname]
call(cmd,stdout=PIPE,stderr=None)
def get_duration(start='00:00:00',end=''):
'''
end can be negative if prefixed with `n` as in `n00:00:04`
which means four seconds from the end of the file.
'''
if end and not end.startswith('n'): #
he,me,se=parse_ts(end)
end_time=datetime(2017,1,1,he,me,se)
elif end.startswith('n'):
he,me,se=parse_ts(end[1:])
end_time=get_file_duration(args.infile)-timedelta(hours=he,minutes=me,seconds=se)
else:
end_time=get_file_duration(args.infile)
hs,ms,ss=parse_ts(start)
start_time=datetime(2017,1,1,hs,ms,ss)
duration=str(end_time - start_time)
if len(duration)==7: duration = '0'+duration
return duration
if __name__ == '__main__':
parse = argparse
parser = argparse.ArgumentParser(formatter_class=argparse.RawDescriptionHelpFormatter,
description='''Cut a section out of MP4 file and return it using ffmpeg
without re-encoding.
Example: extract from start to 00:11:44
% python mp4_cut.py -e 11:44 -i L.mp4 -o foo.mp4
Example: extract from 00:15:00 to 00:17:34
% python mp4_cut.py -s 15:00 -e 17:34 -i L.mp4 -o foo.mp4
You can also take the complement of the selected slice by using the
--invert flag
% python mp4_cut.py --inverst -s 15:00 -e 17:34 -i L.mp4 -o foo.mp4
The two complementary parts are joined to make the output file.''')
parser.add_argument("-i","--input-file",
dest="infile",
help='input file',
default='',
)
parser.add_argument("-o","--output-file",
dest="outfile",
help='output file',
default='',
)
parser.add_argument("-s","--start-time",
dest="start_time",
help='hh:mm:ss',
default='00:00:00',
)
parser.add_argument("-e","--end-time",
dest="end_time",
help='hh:mm:ss',
default='',
)
parser.add_argument("-c","--chunk_duration",
help='Divide into <n> chunks of this duration hh:mm:ss. Overrides other flags!',
default='',
)
parser.add_argument("--invert",
dest='invert',
default=False,
action='store_true',
help="return complement of indicated section")
args = parser.parse_args()
if args.chunk_duration:
# this over-rides other options
hc,mc,sc=parse_ts(args.chunk_duration)
start_time=datetime(2017,1,1,0,0,0)
end_time=datetime(2017,1,1,hc,mc,sc)
file_length = get_file_duration(args.infile)
dt = timedelta(hours=hc,minutes=mc,seconds=sc)
outfilename_head = args.outfile.replace('.mp4','')
n=0
while end_time < file_length:
run_cmd_dt(start_time,end_time,args.infile,'%s_%03d.mp4'%(outfilename_head,n))
start_time = end_time
end_time = start_time + dt
n += 1
sys.exit()
duration = get_duration(args.start_time,args.end_time)
if args.invert:
if args.start_time=='00:00:00': # tail section
duration = '23:00:00'
cmd=['ffmpeg','-ss',format_ts(args.end_time),'-t',duration,'-i',
args.infile,'-acodec','copy','-vcodec','copy',
args.outfile]
call(cmd,stdout=PIPE,stderr=None)
else: # middle section
start_time='00:00:00'
filename1=tempfile.mktemp('.mp4',dir=os.getcwd())
filename2=tempfile.mktemp('.mp4',dir=os.getcwd())
run_cmd(start_time,args.start_time,args.infile,filename1)
run_cmd(args.end_time,'23:00:00',args.infile,filename2)
fname= tempfile.mktemp(suffix='.txt',dir=os.getcwd())
with open(fname,'w') as fd:
fd.write('file '+os.path.split(filename1)[1]+'\n')
fd.write('file '+os.path.split(filename2)[1]+'\n')
fd.close()
# ffmpeg -safe 0 -f concat -i list.txt -c copy outfile.mp4
cmd=['ffmpeg','-safe','0','-f','concat','-i',fname,'-c','copy',args.outfile ]
call(cmd,stdout=PIPE,stderr=None)
for i in (filename1,filename2,fname):
os.unlink(i)
else:
run_cmd(args.start_time,args.end_time,args.infile,args.outfile)