#!/usr/bin/perl

##
 # mplayer-youtube.pl by Gavrilo Prodanovic 
 # This program is free software. It comes without any warranty, to
 # the extent permitted by applicable law. You can redistribute it
 # and/or modify it under the terms of the Do What The Fuck You Want
 # To Public License, Version 2, as published by Sam Hocevar. See
 # http://sam.zoy.org/wtfpl/COPYING for more details.
##

$res = 480;
$chmin = 60;
$cache= 1024;
while ($_ = shift @ARGV)
{
	if    (/^-h/)         { &help_print(); }
	elsif (/^http:\/\//)  { $link = $_; }
	elsif (/^-r/)         { $res = shift @ARGV; }
	elsif (/^-cache/)     { $cache = shift @ARGV; }
	elsif (/^-cache-min/) { $chmin = shift @ARGV; }
	else                  { push @MPARG, $_; } 

}

&help_print() unless defined $link;

$fin_res = 5  if $res == 240;
$fin_res = 34 if $res == 360;
$fin_res = 18 if $res == 480;
$fin_res = 22 if $res == 720;
$fin_res = 37 if $res == 1080;

&help_print() unless defined $fin_res;

$mp_link=`youtube-dl --max-quality=$fin_res -g $link`;
chomp $mp_link;

system "mplayer", "-cache", $cache, "-cache-min", $chmin, @MPARG, $mp_link;


sub help_print()
{
	print "Use $0 LINK [option] [mplayer option]\n";
	print "\t-r <240|360|480|720|1080> set resolution; default: $res\n";
	print "\t-cache <kBytes> set mplayer cache; default: $cache\n";
	print "\t-cache-min <1-100> set mplayer cache-min; default: $chmin\n";
	print "Depends: mplayer and youtube-dl\n";
	exit 0;
}
