Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python
- # -*- coding: utf-8 -*-
- '''
- Concatenate MP4 files
- usage: mp4cat.py [-h] [-o OUTPUT] [-t TMPDIR] [-d] filename [filename ...]
- positional arguments:
- filename MP4 files to be concatenated
- optional arguments:
- -h, --help show this help message and exit
- -o OUTPUT, --output OUTPUT
- output file name (default: out.mp4)
- -t TMPDIR, --tmpdir TMPDIR
- temporay directory (deafult: /tmp)
- -k, --keep-tempfile do not remove temporary file(s)
- '''
- import os, os.path, argparse, re, time
- from subprocess import getoutput, check_call
- from tempfile import gettempdir, gettempprefix
- def get_args():
- dofile = 'out.mp4'
- dtmpdir = gettempdir()
- parser = argparse.ArgumentParser(description='Concatenate MP4 files')
- parser.add_argument('filename',
- help='MP4 files to be concatenated',
- nargs='+')
- parser.add_argument('-o', '--output',
- help='output file name (default: {})'.format(dofile),
- default=dofile)
- parser.add_argument('-t', '--tmpdir',
- help='temporay directory (deafult: {})'.format(dtmpdir),
- default=dtmpdir)
- parser.add_argument('-k', '--keep-tempfile',
- help='do not remove temporary file(s)',
- action='store_true')
- args = parser.parse_args()
- if os.path.exists(args.output):
- raise SystemExit('ERROR: Output file name already exists.')
- if len(args.filename) < 2:
- raise SystemExit('ERROR: Specified only a single file.')
- return (args)
- def get_duration(ifile):
- slist = []
- print(ifile)
- if os.path.exists(ifile):
- finfo = getoutput('MP4Box -info "' + ifile + '"')
- dlist = re.findall(r'(Track # \d+) .* Duration (\d+:\d{2}:\d{2}\.\d{3})', finfo)
- else:
- raise SystemExit('ERROR: File not found.')
- for tr, d in dlist:
- h, m, s = d.split(':')
- sec = int(h) * 3600 + int(m) * 60 + float(s)
- print (tr, sec)
- slist.append(sec)
- return min(slist)
- def main():
- tmprefix = "{}.{}".format(gettempprefix(), time.time())
- tlist = []
- args = get_args()
- for i in range(1, len(args.filename)):
- afile = args.filename[0] if i == 1 else "{}.{}.mp4".format(tmprefix, i - 1)
- dur = get_duration(afile)
- nfile = "{}.{}.mp4".format(tmprefix, i)
- cmd = ('MP4Box',
- '-tmp', args.tmpdir,
- '-new', nfile,
- '-add', '{}:dur={}'.format(afile, dur),
- '-cat', args.filename[i])
- print('-tmp {0[2]} -new {0[4]} -add {0[6]} -cat {0[8]}'.format(cmd))
- check_call(cmd)
- tlist.append(nfile)
- print('Renaming result file to "{}"...'.format(args.output))
- os.rename(tlist[-1], args.output)
- if not args.keep_tempfile:
- for t in tlist[:-1]:
- print('Removing templrary file {}...'.format(t))
- os.remove(t)
- if __name__ == '__main__':
- main()
Advertisement
Add Comment
Please, Sign In to add comment