How to join avi files + python automation code

I downloaded videos from rapidshare.com, but like most large file size videos there, the videos I got were split into parts. This is because rapidshare.com has a file size upload limit of 250 MB AFAIK.

So I needed some way to join my avi files which I got from rapidshare.com. I think I could’ve lived with the fact that I can just let my avi videos be, without joining file1.avi.part1 to file1.avi.part2 together, for example. All I would’ve done is create a playlist of my split avi files and play them consecutively using MPlayer or VLC for example. I wouldn’t really care if there was a 1 second gap between the playback of file1.avi.part1 and file1.avi.part2. The problem was, I can only play file1.avi.part1 and not file1.avi.part2. This was a real pain since I wanted to watch the whole video/s.

The solution? Home grown in Linux (^)__(^)

Well, actually we need the

cat

command and we need

mencoder

installed. These shouldn’t be a problem nowadays.

For those out there who only want to join a few videos together, the first step is to issue this simple command:

$cat file1.avi.part1 file1.avi.part2 > file1.avi

where file1.avi is the temporary file which combines file1.avi.part1 and file1.avi.part2. But we’re not done yet, as the audio and video might not sync coming from file1.avi.part1 to file1.avi.part2. You can use

cat

on as many files as you want or on as many as your PC can accommodate btw.
What we do is this:

$ mencoder -forceidx -oac copy -ovc copy file1.avi -o file1_final.avi

in case you don’t trust me, you can always consult your man page (^)__(^)
The previous command synchronizes the audio and the video of file1.avi by streamcopying its audio and video into file1_final.avi.
And that should be it! Now you (and me) have a single contiguous file which you (or me) can watch.
But for users out there who mind all the typing, since they’ve got several avi files to join together, I’ve made a python program for you guys:

#! /usr/bin/python

try:
	import commands, os, sys, string, getopt
except ImportError, msg1:
	exit(msg1)

def help_message():
    print '''This program joins split avi files. The file names of the split avi files to be joined should be in the manner:
	(filename1).avi.part1, (filename1).avi.part2,...
	or
	(filename1).avi.001, (filename1).avi.002,...
	The point is, the filenames are separated by '.' from their file (avi) type extension. The final combined video has the format (filename1)_final.avi.
	This program also assumes there are at least 2 split files you want to join in a single file. Otherwise, it will just copy the single avi file into (filename1)_final.avi.
	A MEncoder installation is required.
    Options:
	-h		displays this help message
	--file=		expects a file containing the list of avi files to be joined
	--version	displays Python version

       e.g. To join avi files in the current directory, listed in split_files.txt:
	 join_avi.py --file=split_files.txt'''
    sys.exit(0)

def getFilenames(split_list):
	file = open(split_list, "r")
	lines = file.readlines()
	try:
		i=True
		for filename in lines:
			namae = filename.split(".")
			if i == True:
				os.system("cat "+namae[0]+"* > _"+namae[0]+"_.avi")
				os.system("mencoder -forceidx -oac copy -ovc copy _"+ namae[0]+"_.avi -o _"+namae[0]+"_final.avi")
				os.system("rm _"+namae[0]+"_.avi")
				i = False
			if i == False:
				if os.system("ls "+namae[0]+"*"):
					i = False
				else:
					i = True
	except ValueError, msg:
		exit(msg)
	file.close()

def isempty(self) :
    return (len(self) == 0) 

try:
	options, xarguments = getopt.getopt(sys.argv[1:],'ha', ['file=','version'])
except getopt.error:
	print "Error: You tried to use an unknown option or the argument for an option that requires it was missing. Try `options.py -h' for more information."
	sys.exit(0)

if isempty(options):
	help_message()

for a in options[:]:
    if a[0] == '-h':
        help_message()

for a in options[:]:
	if a[0] == '--file' and a[1] != '':
		getFilenames(a[1])
		options.remove(a)
		break
	elif a[0] == '--file' and a[1] == '':
		print '--file expects an argument'
		sys.exit(0)

for a in options[:]:
    if a[0] == '--version':
        print 'join_avi.py version 0.5'
        sys.exit(0)

If you have comments/suggestion/questions, please feel free to post and ask them.

You may also download the python source code from above here=> join_avi.odt. Just remember to save it as a text file with a .py extension for the Python interpreter. Unfortunately, WordPress only accepts jpg, jpeg, png, gif, pdf, doc, ppt, and odt for file uploads so I wasn’t able to upload the join_avi.py code.

Just be sure to remember that indention is very important to Python. If you don’t want to download the source code, you can view this page’s source code (in Firefox, right-click page then click View Page Source) and just copy the original and correct code with proper indentions, to a text editor, and save it with a .py extension.

Tags: , , , ,

14 Responses to “How to join avi files + python automation code”

  1. f241vc15 Says:

    thanks! I have tried watching videos using the mencoder method I mentioned above and they seemed fine for my naked eye. However, as far as I can remember, using only cat to join video files didn’t produce a ‘smooth’ transition effect from one video file to the other. It could be just the encoding of my videos (which were avi btw) but I would think this will happen to other videos as well. Having the same md5sums is good, but what really matters is if the video gets concatenated in a good way, producing one coherent video out of say, two, right? In that case, using cat and md5sum to check the files would probably be not enough. Just my opinions.

  2. Morgan Storey Says:

    I tried cat and it works with some but not all codecs, some version of divx/xvid seem to not work, probably due to the index file, the file cat’s and finishes up the size both files would have been but when played it is only the length of the first file.
    I did
    # mencoder -oac copy -ovc copy file1.avi file2.avi (next file can go here) -o final_movie.avi

  3. f241vc15 Says:

    Hi Morgan,
    Thanks for the heads-up. Yes I forgot to mention that not all possible video and audio codecs will be accommodated by my script/technique, especially some other esoteric codecs. So you instead used my technique without the “forceidx” option included right? Did it go well?

  4. hads Says:

    I believe what Morgan Storey was saying (and is what I do myself) is that there is no need to do the cat to start with, you can pass multiple files to mencoder and it will join them for you.

    hads

  5. f241vc15 Says:

    Hi hads,
    I see, but I wonder if removing the ‘cat’ part and going directly to mencoder will work for all (if not most) video files? I also experienced the one Morgan Storey mentioned, that when just using ‘cat’ between 2 files, the files concatenate correctly (in terms of filesize) but the resulting file only plays the first video file.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s


%d bloggers like this: