Cutting MTS file for Youtube

One thing I really hate about youtube (I think many others do too) is the crazy 10 minute limit. I know it as recently extended to 15 minutes but so what! But to be fair, even with this limitation, youtube is still probably the best site for video sharing.

It is especially annoying to me since we try to have a student presentation every week and post our videos on Youtube.  The videos are typically an hour long and cutting all these can easily waste someone couple hours. Youtube is nice enough to accept MTS file but without a way of cutting it, what is the point.

After some searches and trials, I tested several windows software. They did the job but still I would prefer something more automatic. So after copying here and there, I compile a python script for that eventually. I use mencoder to cut the file. But since mencoder doesn’t seem to be able to cut MTS file, I have to convert it to mp4 first (again using mencoder). The script seems to work fine for my JVC HM200BU. The output file is big and youtube will take long time to process those files. But I care less about that. It is not my tiny desktop running transcoding anyway. So here is the python script

#!/usr/bin/env python
import sys
   import os
   import re
   import commands
   import string
   import math
   import datetime

def cutVideo(movie,segment_time):
   cmd="mplayer -frames 0 -identify %s.mp4 2>&1|grep ID_LENGTH|cut -f2 -d=" % movie # get video length
   print cmd
   len=commands.getoutput(cmd);
   print len
   movie_len=datetime.timedelta(seconds=math.ceil(string.atof(len)))
   start_time=datetime.timedelta(seconds=0)
   cut_len=datetime.timedelta(minutes=segment_time)

   print movie_len
   count=1
   while 1:
	   cmd = "mencoder -ss %s -endpos %s -oac copy -ovc copy %s.mp4 -o %s_%d.avi" % (start_time,cut_len,movie,movie,count)
	   os.system(cmd) # extract segment

   	   count=count+1
   	   start_time = start_time + cut_len

           if start_time > movie_len:
   		  break

if __name__ == "__main__":
   fin=sys.argv[1]
   bname=re.sub('\.mts$','',fin,1)
   bname=re.sub('\.MTS$','',bname,1)
   fout="%s.mp4" % bname
   cmd="mencoder %s -demuxer lavf -oac copy -ovc copy -of lavf=mp4 -o %s" % (fin,fout)
   os.system(cmd) # convert to mp4
   cutVideo(bname,10) # cut video into 10 minute segments
   cmd="rm %s" % fout
   os.system(cmd) # remove tmp file

Save the file as cutMTS.py and change it to “run” permission (chmod 755 cutMTS.py). To cut a file 00001.MTS, simple type

./cutMTS.py 00001.MTS

It will generate several avi files 00001_1.avi, 00001_2.avi, and so on. Each of them will be 10 minutes long. If one wants to change the length of the video segment, simply change the argument in the line cutVideo(bname, 10). For example, for 15 minute segment, change 10 to 15.

Leave a Reply

Your email address will not be published. Required fields are marked *