Sponsored By

Sign in to follow this  
shanenin

Watch Widescreen Movies More Full Screen

Recommended Posts

I have a computer connected to my tv which I have my media library on. I personally prefer more of my screen being filled then a very widescreen movie shows. If you use mplayer and have avi files. This program will write a config file for each avi file that will tell mplayer how much to crop it

#!/usr/bin/env python

# authored by shane lindberg

# This script makes configuration files for mplayer. In particular it makes a configuration that crops widescreen
# avi files so they will better fit your 4:3 aspect tv or computer moniter
# to run this program you need to to be in the directory that contains your avi files. Then just simply run the command
# it will check for the dimensions of the avi file using avitype, I think this is a part of transcode. If avitype is not
# installed the script will not work properly. This does not affect your media it only makes a config file that mplayer
# will use. At any time you can simply do 'rm *conf' to remove all of the config files this program created
# then you will be back to your old widescreen self

import os
import sys

current_dir = os.getcwd()

# this python function gets the dimensions of a video file and returns them as a tuple (width,height)
# it uses the linux video program avitype (I think this is part of the transcode package)
# getdimensions.py
def getdimensions(video_file):

   import commands
   avitype_command= '/usr/bin/avitype "%s" | grep WxH' % video_file
   dimensions = commands.getoutput(avitype_command)
   width = int(dimensions[-7:-4])
   height = int(dimensions[-3:])
   WxH = (width,height)
   return WxH

# this function finds all media in a given directory by file extention. It then places this media in a list
def movie_find(directory):
   ls_dir = os.listdir(directory)
   dir_list =[]
   for i in ls_dir:
       if i.endswith('.avi'):
           dir_list.append(i)
   return dir_list

# this part checks to make sure the user has root privleges, if not it exits the script
current_user = os.geteuid()


#you may want to remove this if statment. It is needed for me because my movie files are in a write protected space
if current_user != 0:
   print "you need to be root to run this script"
   sys.exit()

# this part checks to make sure you are in the directory of the files you want to make .conf files for
print "is this the directory which contains the files you want to make .confs for"
print current_dir
answer = raw_input("enter 1 to continue")
if answer != '1':
   print "change to the correct directory then restart the script"
   sys.exit()

movie_list = movie_find(current_dir)

for i in movie_list:
   conf_name = "%s.conf" %i
   wxh = getdimensions(i)
   width = wxh[0]
   # you can change the amount of crop by adjusting the number multiplied by width. The lower the number
   # the more of a crop you will get. If the number is at the max 1, it will not be cropped at all
   cropped_width = int(.80 * width)
   print_tuple = (cropped_width,wxh[1])
   conf_file = open(conf_name, "w")
   conf_file.write("vf=crop=%s:%s\n"%print_tuple)
   conf_file.close()

Share this post


Link to post
Share on other sites

Are you looking for a way to make mplayer config files with c++ ? Is there any specific reason you want to port this to c++ ?

Share this post


Link to post
Share on other sites
More or less for the learning experience.

<{POST_SNAPBACK}>

that is a good reason :-)

even my python script depends on a program called avitype. There may be a way to do the whole thing in c++ , but I am not sure.

After reading your post I thought to goto the library and get a c++ book and try to rewrite it, purely for "a learning experience". Let me know how things go

Share this post


Link to post
Share on other sites
Can someone please roughly explain the equivalent of this code into C++, even just the key parts would be helpful. :)

<{POST_SNAPBACK}>

Edit: Replaced the C program with a C++ program, as requested.

This is a mess, but it kinda works. For the life of me I can't figure out how avifile's error handling or memory management work -- it blows core all over the place when I look at it funny. I suppose it might be documented somewhere, but the docs I have here don't even accurately describe the interfaces of the installed version, let alone the behavior. Anyway, since it isn't going work terribly well, I didn't bother cleaning it up.

#include <fstream>
#include <iostream>
#include <string>

#include <avm_except.h>
#include <avifile.h>
#include <image.h>
#include <infotypes.h>

#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
#include <unistd.h>

const int CropX = 0.8;
const string FileExtension = "avi";

using namespace std;

static bool compare_extension(string&, string&);

int main(int argc, char * argv[])
{
   DIR * directory;
   struct dirent * dentry;

   directory = opendir(".");
   while (dentry = readdir(directory)) {
       struct stat stat_buf;
       string fname = dentry->d_name;
       string ext = FileExtension;
       stat(fname.c_str(), &stat_buf);
       if (S_ISREG(stat_buf.st_mode) &&
           compare_extension(fname, ext))
       {
           avm::IReadFile * avi = avm::CreateReadFile(fname.c_str());
           avm::IReadStream * stream = avi->GetStream(0, avm::IStream::Video);
           stream->StartStreaming();
           avm::CImage * frame = stream->GetFrame(true);

           ofstream conf_file((fname + ".conf").c_str());
           conf_file << "vf=crop="
                     << static_cast<int>(frame->Width()*CropX)
                     << ":"
                     << frame->Height()
                     << endl;
           conf_file.close();

           frame->Release();

           stream->StopStreaming();

           delete stream;
           // delete avi;
       }
   }

   return 0;
}

// I have a feeling this is redundant, but I don't have my ref material with me.
bool compare_extension(string& str, string& ext)
{
   if (str.size() <= ext.size()) {
           return false;
   }

   string::reverse_iterator sr = str.rbegin();  
   string::reverse_iterator er = ext.rbegin();  

   while (er != ext.rend()) {
       if (*er != *sr) {
           return false;
       }
       er++;
       sr++;
   }
   return true;
}

Edited by jcl

Share this post


Link to post
Share on other sites

I suppose a big advantage to using C is the vast suppy of librarys. I ended up haveing to use a program 'avitype', because of the lack of a python module. But I suppose using a program or a c library isn't a whole lot different.

I will have to take a crack at C one of these days. I tried it once as my first language, but lost intest. Now from using python a bit, I think it would be more interesting, and I would understand a bit more.

Share this post


Link to post
Share on other sites
Where did you find the resource avifile.h?
#include <avifile.h>

<{POST_SNAPBACK}>

/usr/include/avifile-0.7/

:)

Share this post


Link to post
Share on other sites

http://paine.wiau.man.ac.uk/pub/doc_vxl/co..._8h-source.html

if you can't find it.. here is one..

here is the main site.http://paine.wiau.man.ac.uk/pub/doc_vxl/contrib/mul/mvl2/html/index.html

Edited by iccaros

Share this post


Link to post
Share on other sites

I revised this script to be much more flexible. First off you no lonager need to have avitype installed. Using the sys.argv and getopt modules, you can now give cropit command line options. for example

cropit /home/shane/movies/kill-bill-vol-*

this code will make a conf file for both kill-bill-vol 1 and 2.

if you downloaded a whole season of television shows you can just use this option

cropit /home/shane/avi/sopranos-season-2/*

you can also pass it an option to the amount you want it cropped

cropit -c 85 /home/shane/movies/sword-fish.avi

I also added a standard --help option

here is the new program

#!/usr/bin/env python
#
# cropit-0.2
#
# author shane lindberg
#
import os, sys, getopt, commands


# this function gets the command options
def get_opts(argv):
                         
   crop = '81'    
   try:    
       opts, args = getopt.getopt(argv, "hc:", ["help", "crop="])
   except getopt.GetoptError:
       usage()                        
       sys.exit(2)
   
   for opt, arg in opts:
       if opt in ("-h", "--help"):
           usage()
           sys.exit()
       elif opt in ("-c", "--crop"):
           crop = arg
   
   return (crop, args)


# this function gives a usage(help) message. This is either called be the user makeing an invalid
# option choice, or by choosing the -h or --help option
def usage():

   print """\n
Usage: cropit [OPTION]... [FILE]...

Options available to cropit

-h, --help         shows options available to cropit .

-c, --crop         tells how much to crop the width of you avi file. The number
                  given is a percentage of the original, ex. -c 85 will crop
                  the width to 85% of the original. -c 100 will crop it to
                  100% of the original, which means no crop. The smaller the
                  number the larger the crop. The default crop is -c 81, or
                  81%. A typical range of 75 to 90 is prefered for most files.\n\n\n """


# this python function gets the dimensions of a video file and returns them as a tuple (width,height)
def getdimensions(v_video_file):

   avitype_command= '/usr/bin/mplayer -identify -frames 0 "%s"' % v_video_file
   output = commands.getoutput(avitype_command)
   split = output.splitlines()
   for i in split:
       if i.startswith('ID_VIDEO_WIDTH='):
           width = int(i.replace('ID_VIDEO_WIDTH=',''))
       if i.startswith('ID_VIDEO_HEIGHT='):
           height = int(i.replace('ID_VIDEO_HEIGHT=',''))  
   return (width, height)

# this function makes the movie.avi.conf file
def make_conf(v_video_file, v_dimensions, v_user_crop):

   base_dir = os.getcwd()
   conf_name = "%s/%s.conf" % (base_dir, v_video_file)
   width = v_dimensions[0]
   height = v_dimensions[1]
   cropped_width = int(float(v_user_crop)/100*width)    
   conf_file = open(conf_name, "w")
   conf_file.write("vf=crop=%s:%s\n" %(cropped_width, height))
   conf_file.close()


def main():
   
   options = get_opts(sys.argv[1:])
   
   for i in options[1]:
       dimensions = getdimensions(i)
       make_conf(i, dimensions, options[0])

main()

Edited by shanenin

Share this post


Link to post
Share on other sites

I made a couple of changes to the original. There was a bug I never noticed before. If you used the absolute path instead of the relative path, it would error out, which in now fixed. Before you were unable to run the program remotely using ssh. I think that was because the program depends on mplayer, since I do not have x11 forwarding it would freeze up at the mplayer command. I changed the video output to this, it seemed to solve the problem

mplayer -vo null

here is the revised version

#!/usr/bin/env python
#
# cropit-0.2.1
#
# author shane lindberg
#
import os, sys, getopt, commands


# this function gets the command options
def get_opts(argv):

crop = '81'
try:
opts, args = getopt.getopt(argv, "hc:", ["help", "crop="])
except getopt.GetoptError:
usage()
sys.exit(2)

for opt, arg in opts:
if opt in ("-h", "--help"):
usage()
sys.exit()
elif opt in ("-c", "--crop"):
crop = arg

return (crop, args)


# this function gives a usage(help) message. This is either called be the user makeing an invalid
# option choice, or by choosing the -h or --help option
def usage():

print """\n
Usage: cropit [OPTION]... [FILE]...

Options available to cropit

-h, --help shows options available to cropit .

-c, --crop tells how much to crop the width of you avi file. The number
given is a percentage of the original, ex. -c 85 will crop
the width to 85% of the original. -c 100 will crop it to
100% of the original, which means no crop. The smaller the
number the larger the crop. The default crop is -c 81, or
81%. A typical range of 75 to 90 is prefered for most files.\n\n\n """


# this python function gets the dimensions of a video file and returns them as a tuple (width,height)
def getdimensions(v_video_file):

avitype_command= '/usr/bin/mplayer -vo null -identify -frames 0 "%s"' % v_video_file
output = commands.getoutput(avitype_command)
split = output.splitlines()
for i in split:
if i.startswith('ID_VIDEO_WIDTH='):
width = int(i.replace('ID_VIDEO_WIDTH=',''))
if i.startswith('ID_VIDEO_HEIGHT='):
height = int(i.replace('ID_VIDEO_HEIGHT=',''))
return (width, height)

# this function makes the movie.avi.conf file
def make_conf(v_video_file, v_dimensions, v_user_crop):

conf_name = "%s.conf" % (v_video_file)
width = v_dimensions[0]
height = v_dimensions[1]
cropped_width = int(float(v_user_crop)/100*width)
conf_file = open(conf_name, "w")
conf_file.write("vf=crop=%s:%s\n" %(cropped_width, height))
conf_file.close()
print os.path.abspath(conf_name)

def main():

options = get_opts(sys.argv[1:])

for i in options[1]:
if i.endswith('.avi') or i.endswith('.mp4'):
dimensions = getdimensions(i)
make_conf(i, dimensions, options[0])

main()

Share this post


Link to post
Share on other sites

If you use freevo, I encorperated the cropit program into the interface. Now you are able to crop your avi files directly through the freevo interface, no other computer needed. I wish I could say my python skills are strong(getting better), but I mainly just copied an example I found on the web. I am trying to upload the pluginn to the freevo sight, but have had some trouble logging on, as of now you can find it here

http://webpages.charter.net/lindbergfamily...crop-0.1.tar.gz

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
Sign in to follow this