url.pl 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. #!/usr/bin/perl
  2. use strict;
  3. use warnings;
  4. use File::Basename;
  5. use WWW::YouTube::Download;
  6. # Sanity check
  7. if (scalar(@ARGV) < 1) {
  8. die('Usage: ' . basename($0) . " url\n");
  9. }
  10. # Command-line parameters
  11. my $url = $ARGV[0];
  12. # Environmental parameters
  13. my $DEBUG = 0;
  14. if ($ENV{'DEBUG'}) {
  15. $DEBUG = 1;
  16. }
  17. # Init the YT object
  18. my $tube = WWW::YouTube::Download->new;
  19. # Parse the video ID
  20. my $id = $tube->video_id($url);
  21. # Fetch metadata
  22. my $meta = $tube->prepare_download($id);
  23. # Find the best stream (i.e. highest resolution, prefer mp4)
  24. my $bestStream = undef();
  25. my $bestResolution = 0;
  26. foreach my $streamID (keys(%{ $meta->{'video_url_map'} })) {
  27. my $stream = $meta->{'video_url_map'}->{$streamID};
  28. my ($res) = $stream->{'resolution'} =~ /^\s*(\d+)/;
  29. if ($DEBUG) {
  30. print STDERR $streamID . ' (' . $stream->{'suffix'} . ')' . ' => ' . $stream->{'resolution'} . ' : ' . $stream->{'url'} . "\n\n";
  31. }
  32. if ( ($res > $bestResolution)
  33. || ($res == $bestResolution && defined($bestStream) && $bestStream->{'suffix'} ne 'mp4'))
  34. {
  35. $bestStream = $stream;
  36. $bestResolution = $res;
  37. }
  38. }
  39. # Return the download URL
  40. print STDOUT $bestStream->{'url'} . "\n";
  41. # Cleanup
  42. exit(0);