Guest User

mp4cat.py

a guest
Mar 29th, 2012
130
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.12 KB | None | 0 0
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. '''
  4. Concatenate MP4 files
  5.  
  6. usage: mp4cat.py [-h] [-o OUTPUT] [-t TMPDIR] [-d] filename [filename ...]
  7.  
  8. positional arguments:
  9.  filename              MP4 files to be concatenated
  10.  
  11. optional arguments:
  12.  -h, --help            show this help message and exit
  13.  -o OUTPUT, --output OUTPUT
  14.                        output file name (default: out.mp4)
  15.  -t TMPDIR, --tmpdir TMPDIR
  16.                        temporay directory (deafult: /tmp)
  17.  -k, --keep-tempfile   do not remove temporary file(s)
  18. '''
  19. import os, os.path, argparse, re, time
  20. from subprocess import getoutput, check_call
  21. from tempfile   import gettempdir, gettempprefix
  22.  
  23. def get_args():
  24.     dofile  = 'out.mp4'
  25.     dtmpdir = gettempdir()
  26.  
  27.     parser = argparse.ArgumentParser(description='Concatenate MP4 files')
  28.     parser.add_argument('filename',
  29.                         help='MP4 files to be concatenated',
  30.                         nargs='+')
  31.     parser.add_argument('-o', '--output',
  32.                         help='output file name (default: {})'.format(dofile),
  33.                         default=dofile)
  34.     parser.add_argument('-t', '--tmpdir',
  35.                         help='temporay directory (deafult: {})'.format(dtmpdir),
  36.                         default=dtmpdir)
  37.     parser.add_argument('-k', '--keep-tempfile',
  38.                         help='do not remove temporary file(s)',
  39.                         action='store_true')
  40.     args = parser.parse_args()
  41.  
  42.     if os.path.exists(args.output):
  43.         raise SystemExit('ERROR: Output file name already exists.')
  44.     if len(args.filename) < 2:
  45.         raise SystemExit('ERROR: Specified only a single file.')
  46.  
  47.     return (args)
  48.  
  49. def get_duration(ifile):
  50.     slist = []
  51.  
  52.     print(ifile)
  53.     if os.path.exists(ifile):
  54.         finfo = getoutput('MP4Box -info "' + ifile + '"')
  55.         dlist = re.findall(r'(Track # \d+) .* Duration (\d+:\d{2}:\d{2}\.\d{3})', finfo)
  56.     else:
  57.         raise SystemExit('ERROR: File not found.')
  58.  
  59.     for tr, d in dlist:
  60.         h, m, s = d.split(':')
  61.         sec = int(h) * 3600 + int(m) * 60 + float(s)
  62.         print (tr, sec)
  63.         slist.append(sec)
  64.  
  65.     return min(slist)
  66.  
  67. def main():
  68.     tmprefix = "{}.{}".format(gettempprefix(), time.time())
  69.     tlist    = []
  70.  
  71.     args = get_args()
  72.  
  73.     for i in range(1, len(args.filename)):
  74.         afile = args.filename[0] if i == 1 else "{}.{}.mp4".format(tmprefix, i - 1)
  75.         dur   = get_duration(afile)
  76.         nfile = "{}.{}.mp4".format(tmprefix, i)
  77.         cmd   = ('MP4Box',
  78.                  '-tmp', args.tmpdir,
  79.                  '-new', nfile,
  80.                  '-add', '{}:dur={}'.format(afile, dur),
  81.                  '-cat', args.filename[i])
  82.         print('-tmp {0[2]} -new {0[4]} -add {0[6]} -cat {0[8]}'.format(cmd))
  83.         check_call(cmd)
  84.         tlist.append(nfile)
  85.  
  86.     print('Renaming result file to "{}"...'.format(args.output))
  87.     os.rename(tlist[-1], args.output)
  88.     if not args.keep_tempfile:
  89.         for t in tlist[:-1]:
  90.             print('Removing templrary file {}...'.format(t))
  91.             os.remove(t)
  92.  
  93. if __name__ == '__main__':
  94.     main()
Advertisement
Add Comment
Please, Sign In to add comment