source: gutenbach/lib/gutenbach @ 04f7e05

debianmacno-cupsweb
Last change on this file since 04f7e05 was 04f7e05, checked in by Jessica B. Hamrick <jhamrick@…>, 14 years ago

Move debian folder into the root, and move all non-debian code into gutenbach/

  • Property mode set to 100755
File size: 10.5 KB
RevLine 
[d988d9d]1#!/usr/bin/perl
[b0d9dda]2# Play the data on STDIN as an audio file
3#
[2e8b589]4# $Id: gutenbach-filter,v 1.26 2009/02/20 00:27:17 geofft Exp root $
5# $Source: /usr/local/bin/RCS/gutenbach-filter,v $
[b0d9dda]6#
7# TODO
8# ----
9# Make this structured code. It's a mess.
10# Repeat what we just played for EXT files too
11# Support HTTP Auth on ogg streams
12# License, cleanup and package
13#
14# Jered Floyd <jered@mit.edu> takes very little credit for this code
[c711ed9]15# apparently neither does Quentin Smith <quentin@mit.edu>
[b0d9dda]16
[d2fa590]17use strict;
18use warnings;
[ba06c7f]19use Image::ExifTool qw(ImageInfo);
20use File::Spec::Functions;
[d2fa590]21use File::Temp qw{tempfile tempdir};
[908107d]22use File::Basename qw(basename);
[ba06c7f]23use LWP::UserAgent;
24use Data::Dumper;
[f6c9736]25use IPC::Open2;
[d2fa590]26use English;
[ba06c7f]27
[e20354c]28use vars qw/$zephyr_class $host $queue $mixer $channel/;
29
[d2fa590]30require "/usr/lib/gutenbach/config/gutenbach-filter-config.pl" or die "Unable to load configuration";
[3a900ef]31
[ba06c7f]32my $ua = new LWP::UserAgent;
33
[0237078]34# This variable contains the pid of the child process (which runs
35# mplayer) once it has been forked, so that we can kill it on SIGTERM
36my $pid;
37
[d2fa590]38# Replace STDERR with a log file in /tmp.
39open(CUPS, ">&STDERR") or die "Unable to copy CUPS filehandle";
[ba06c7f]40close(STDERR);
[2e8b589]41open(STDERR, ">>", "/tmp/gutenbach.log") or warn "Couldn't open log: $!";
[ba06c7f]42
[d2fa590]43# Set the TERM environment (for the benefit of mplayer?)
44# I don't know why we do this --quentin
[ba06c7f]45$ENV{"TERM"}="vt100";
[b0d9dda]46
[148111e]47print STDERR "STDERR FROM SPOOL FILTER\n";
48
[d2fa590]49# CUPS provides us with these arguments:
50#
51# argv[1]
52# The job ID
53# argv[2]
54# The user printing the job
55# argv[3]
56# The job name/title
57# argv[4]
58# The number of copies to print
59# argv[5]
60# The options that were provided when the job was submitted
61# argv[6]
62# The file to print (first program only)
63#
64# The scheduler runs one or more of these programs to print any given
65# job. The first filter reads from the print file and writes to the
66# standard output, while the remaining filters read from the standard
67# input and write to the standard output. The backend is the last
68# filter in the chain and writes to the device.
[b0d9dda]69
[06133dc]70printf(STDERR "Got \@ARGV: %s\n", Dumper(\@ARGV));
71
[d2fa590]72my %arguments = (
[e20354c]73                 "job-id" => $ARGV[0],
[d2fa590]74                 user => $ARGV[1],
[e20354c]75                 "job-title" => $ARGV[2],
[d2fa590]76                 copies => $ARGV[3],
77                 options => {split(/[= ]/, $ARGV[4])},
78                 file => $ARGV[5],
79                );
80
81# If we weren't given a filename, we need to read from stdin. Since
82# mplayer really wants a file, let's write out to a temporary file
83# first.
84if (!$arguments{"file"}) {
85  my ($fh, $file) = tempfile("gutenbachXXXXX", UNLINK => 1); # Ask File::Temp for a safe temporary file
86  my $buf;
87  while (read(STDIN, $buf, 1024*1024)) { # Read 1M at a time and put it in the temporary file
88    print $fh $buf;
[06133dc]89  }
[d2fa590]90  close($fh);
[e20354c]91  $arguments{"file"} = $file;
[06133dc]92}
93
[d2fa590]94printf(STDERR "Got \%arguments: %s\n", Dumper(\%arguments));
[b011fb0]95
[d2fa590]96# Open up a zwrite command to announce the current track.
97my @zwrite_command = (qw(/usr/bin/zwrite -d -n -c), $zephyr_class, "-i", $queue.'@'.$host, "-s", "Gutenbach Music Spooler");
[80bbeea]98
[d2fa590]99print STDERR "Invoking @zwrite_command\n";
100open(ZEPHYR, "|-", @zwrite_command) or die "Couldn't launch zwrite: $!";
[b0d9dda]101
[3778176]102my $status;
103if (exists($arguments{"options"}{"job-originating-host-name"})) {
104    print(ZEPHYR $arguments{"user"},"\@",$arguments{"options"}{"job-originating-host-name"}," is playing:\n");
105    $status = "User: ".$arguments{"user"}."\@".$arguments{"options"}{"job-originating-host-name"};
106} else {
107    print(ZEPHYR $arguments{"user"}," is playing:\n");
108    $status = "User: ".$arguments{"user"};
109}
[2e8b589]110
[d2fa590]111# SIGHUP handler, in case we were aborted
[f014bc4]112sub clear_status {
[0237078]113  kill 15, $pid if $pid;
[d2fa590]114  my @zwrite_command = (qw(/usr/bin/zwrite -d -n -c), $zephyr_class, "-i", $queue.'@'.$host, "-s", "Gutenbach Music Spooler");
115  open(ZEPH, "|-", @zwrite_command);
116  print(ZEPH "Playback aborted.\n");
117  close(ZEPH);
118  die;
[f014bc4]119}
[0237078]120
[f014bc4]121$SIG{HUP} = \&clear_status;
[0237078]122$SIG{TERM} = \&clear_status;
[f014bc4]123
[ba06c7f]124# Read the metadata information from the file.
[e20354c]125my ($filepath) = $arguments{"file"};
[ba06c7f]126my ($fileinfo) = ImageInfo($filepath);
127my ($magic) = $fileinfo->{FileType};
[e20354c]128my ($tempdir);
129my ($newpath);
[b0d9dda]130
[ba06c7f]131if ($magic) {
[d2fa590]132  # $magic means that Image::ExifTool was able to identify the type of file
133  printf(ZEPHYR "%s file %s\n", $magic, $arguments{"job-title"});
134  $status .= sprintf(" Filetype: %s.", $magic);
135  $status .= sprintf(" Filename: %s.", $arguments{"job-title"});
136
137  if (exists $fileinfo->{'Title'}) {
138    printf(ZEPHYR "\@b{%s}\n", $fileinfo->{'Title'}) if exists $fileinfo->{'Title'};
139    $status .= sprintf(" Title: %s.", $fileinfo->{'Title'});
140  }
141  foreach my $key (qw/Artist Album AlbumArtist/) {
142    if (exists $fileinfo->{$key}) {
143      printf(ZEPHYR "%s\n", $fileinfo->{$key}) if exists $fileinfo->{$key};
144      $status .= sprintf(" %s: %s\n", $key, $fileinfo->{$key});
[ba06c7f]145    }
[d2fa590]146  }
147
[e20354c]148  $tempdir = tempdir();
[d2fa590]149  #awful hack -- geofft
150  #== -- quentin
151  # This code appears to create a new temporary directory and symlink
152  # the job file into the temporary directory under the original
153  # filename. I think this is because mplayer sometimes uses the file
154  # extension to identify a filetype.
[e20354c]155  $newpath = $tempdir . '/' . basename($arguments{"job-title"});
[d2fa590]156  symlink($filepath, $newpath);
157  $filepath = $newpath;
[ba06c7f]158}
[d2fa590]159elsif ($arguments{copies} == 42) {
160  # This is a flag that is set by jobs queued by split_playlist(); it tells us to not try to split the playlist again.
161  # Call resolve_external_reference to apply some heuristics to determine the filetype.
162  $filepath = resolve_external_reference($filepath, \%arguments);
163  if ($filepath =~ m|http://www\.youtube\.com/watch\?v=|) {
164    # YouTube URLs are resolved by the youtube-dl command.
165    # Launch youtube-dl
166    open(YTDL, "-|", "youtube-dl", "-g", $filepath) or die "Unable to invoke youtube-dl";
167    # Read the title (currently not doing so because youtube-dl doesn't know how to get the title.
168    my $title = ""; # <YTDL>
169    # Print the title to zephyr and the status string.
170    print ZEPHYR "YouTube video $filepath\n$title";
171    $status .= " YouTube video $filepath. $title.";
172    # youtube-dl prints the URL of the flash video, which we pass to mplayer as a filename.
173    $filepath = <YTDL>;
174    chomp $filepath;
175  } else { # Doesn't appear to be a YouTube URL.
176    print STDERR "Resolved external reference to $filepath\n";
177    printf(ZEPHYR "%s\n", $filepath);
178    $status .= sprintf(" External: %s\n", $filepath);
179  }
[ba06c7f]180}
[d2fa590]181elsif (-T $filepath) { # If the file appears to be a text file, treat it as a playlist.
182  split_playlist($filepath, \%arguments);
183  close(ZEPHYR);
184  # See http://www.cups.org/documentation.php/api-filter.html#MESSAGES
185  print CUPS "NOTICE: $status\n";
186  exit 0;
[7e27cc3]187}
[a041c73]188
[ba06c7f]189close(ZEPHYR);
[d2fa590]190print CUPS "NOTICE: $status\n";
191play_mplayer_audio($filepath, \%arguments);
[b0d9dda]192
[d2fa590]193# Remove the symlink we made earlier for the filetype.
[a041c73]194if ($magic) {
[d2fa590]195  unlink($newpath);
196  rmdir($tempdir);
[a041c73]197}
198
[b0d9dda]199# Play an external stream reference
[ba06c7f]200sub resolve_external_reference {
[d2fa590]201  # Retrieve those command line opts.
202  my ($filepath, $arguments) = @_;
203
[e20354c]204  my ($format, $uri, $userpass);
[d2fa590]205
206  open(FILE, "<", $filepath) or die "Couldn't open spool file";
207  if (<FILE> =~ /^(\S+)/) {
208    # Take the leading non-whitespace as a URL
209    $uri=$1;
210
211    if ($uri =~ m|http://www\.youtube\.com/watch\?v=|) {
212      return $uri;
[b281379]213    }
[b0d9dda]214
[d2fa590]215    # Fetch the URL with a HEAD request to get the content type
216    my $response = $ua->head($uri);
217
218    my $contenttype=($response->content_type() or "unknown");
219
220    if ($contenttype eq "audio/mpeg") { $format="MP3" }
221    elsif ($contenttype eq "application/x-ogg") { $format="OGG" }
222    elsif ($contenttype eq "application/ogg") { $format="OGG" }
223    elsif ($contenttype eq "audio/x-scpls") { $format="SHOUTCAST" }
224    else {
225      print ZEPHYR
226        "Unknown Content-Type $contenttype for URI $uri\n";
[b0d9dda]227    }
[d2fa590]228  } else { # Unable to match the URL regex
229    print ZEPHYR "Couldn't read URI for external reference\n";
230    # Return the existing path, in the hopes that mplayer knows what to do with it.
231    return $filepath;
232  }
233
234  if ($format eq "SHOUTCAST") {
235    print ZEPHYR "Shoutcast playlist...\n";
236    return get_shoutcast($uri);
237  } elsif ($format eq "MP3") {
238  } elsif ($format eq "OGG") {
239  } else {
240    print ZEPHYR "Unrecognized stream format: $format\n";
241  }
242  return $uri;
[b0d9dda]243}
244
[7e27cc3]245sub split_playlist {
[d2fa590]246  my ($file, $arguments) = @_;
247
248  my $i = 0;
249
250  open(FILE, "<", $filepath) or die "Couldn't open spool file";
251  while (<FILE>) {
252    chomp;
253    if (/^([^#]\S+)/) {
254      printf (STDERR "Found playlist line: %s\n", $_);
255      open(LPR, "|-", 'lpr', '-P'.$queue.'@localhost', '-#', '42', '-J', $arguments->{"job-title"}, '-o', 'job-priority=100');
256      print LPR $1;
257      close(LPR);
258      $i++;
[7e27cc3]259    }
[d2fa590]260  }
261  printf(ZEPHYR "Playlist containing %d valid entries, split into separate jobs.\n", $i);
[7e27cc3]262}
263
[53d7625]264# Process a Shoutcast playlist
265# get_shoutcast(URI)
266sub get_shoutcast {
267  my $uri = shift(@_);
[d2fa590]268
[ba06c7f]269  my $response = $ua->get($uri);
[e20354c]270  my (@titles, @uris);
[ba06c7f]271
272  foreach (split("\n", $response->content())) {
[53d7625]273      if (/^File\d+=(\S+)/) {
274          push(@uris, $1);
275      }
276      if (/^Title\d+=(.+)$/) {
277          push(@titles, $1);
278      }
279  }
[d2fa590]280
[53d7625]281  # choose a random server
[e20354c]282  my $server = int(rand scalar(@uris));
[53d7625]283  # print the name of the stream if available
284  print ZEPHYR "$titles[$server]\n";
285  return $uris[$server];
286}
[b0d9dda]287
[ba06c7f]288sub play_mplayer_audio {
[d2fa590]289  my ($filepath, $opts) = @_;
[b0d9dda]290
[d2fa590]291  # Open up a zwrite command to show the mplayer output
292  my @zwrite_command = (qw(/usr/bin/zwrite -d -n -c), $zephyr_class, "-i", $queue.'@'.$host, "-s", "Gutenbach Music Spooler");
293
[0237078]294  print STDERR "Invoking (from play_mplayer_audio): @zwrite_command\n";
[d2fa590]295
296  # fork for mplayer
[0237078]297  $pid = open(MP3STATUS, "-|");
[d2fa590]298  unless (defined $pid) {
[0237078]299    open(ZEPHYR, "|-", @zwrite_command) or die "Couldn't launch zwrite: $!";
[d2fa590]300    print ZEPHYR "Couldn't fork: $!\n";
301    close(ZEPHYR);
302    return;
[b0d9dda]303  }
304
[d2fa590]305  if ($pid) { #parent
306    # Check if there were any errors
307    if ($_ = <MP3STATUS>) {
[0237078]308      open(ZEPHYR, "|-", @zwrite_command) or die "Couldn't launch zwrite: $!";
[d2fa590]309      print ZEPHYR "Playback completed with the following errors:\n";
310      while (<MP3STATUS>) {
311        print ZEPHYR $_;
312      }
[0237078]313      close(ZEPHYR);
[d2fa590]314    } else {
[0237078]315      open(ZEPHYR, "|-", @zwrite_command) or die "Couldn't launch zwrite: $!";
[d2fa590]316      print ZEPHYR "Playback completed successfully.\n";
[0237078]317      close(ZEPHYR);
[d2fa590]318    }
319    close(MP3STATUS) || print ZEPHYR "mplayer exited $?\n";
320  }
321  else { # child
322    # redirect STDERR to STDOUT
323    open STDERR, '>&STDOUT';
324    # make sure that mplayer doesn't try to intepret the file as keyboard input
325    close(STDIN);
326    open(STDIN, "/dev/null");
327
[4ac44b2]328    my @args = (qw|/usr/bin/mplayer -vo fbdev2 -zoom -x 1024 -y 768 -framedrop -nolirc -cache 512 -ao alsa -really-quiet |, $filepath);
[d2fa590]329    #print STDERR "About to exec: ", Dumper([@args]);
330    exec(@args) ||
331      die "Couldn't exec";
332  }
333}
Note: See TracBrowser for help on using the repository browser.