source: server/lib/gutenbach @ b58aada

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

Use perl bindings for gbr and gbrm in addition to gbq. Update README.

  • Property mode set to 100755
File size: 10.6 KB
Line 
1#!/usr/bin/perl
2# Play the data on STDIN as an audio file
3#
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 $
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
15# apparently neither does Quentin Smith <quentin@mit.edu>
16
17use strict;
18use warnings;
19use Image::ExifTool qw(ImageInfo);
20use File::Spec::Functions;
21use File::Temp qw{tempfile tempdir};
22use File::Basename qw(basename);
23use LWP::UserAgent;
24use Data::Dumper;
25use IPC::Open2;
26use English;
27
28use vars qw/$zephyr_class $host $queue $mixer $channel/;
29
30require "/usr/lib/gutenbach/config/gutenbach-filter-config.pl" or die "Unable to load configuration";
31
32my $ua = new LWP::UserAgent;
33
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
38# Replace STDERR with a log file in /tmp.
39open(CUPS, ">&STDERR") or die "Unable to copy CUPS filehandle";
40close(STDERR);
41open(STDERR, ">>", "/tmp/gutenbach.log") or warn "Couldn't open log: $!";
42
43# Set the TERM environment (for the benefit of mplayer?)
44# I don't know why we do this --quentin
45$ENV{"TERM"}="vt100";
46
47print STDERR "STDERR FROM SPOOL FILTER\n";
48
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.
69
70printf(STDERR "Got \@ARGV: %s\n", Dumper(\@ARGV));
71
72my %arguments = (
73                 "job-id" => $ARGV[0],
74                 user => $ARGV[1],
75                 "job-title" => $ARGV[2],
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;
89  }
90  close($fh);
91  $arguments{"file"} = $file;
92}
93
94printf(STDERR "Got \%arguments: %s\n", Dumper(\%arguments));
95
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");
98
99print STDERR "Invoking @zwrite_command\n";
100open(ZEPHYR, "|-", @zwrite_command) or die "Couldn't launch zwrite: $!";
101
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}
110
111# SIGHUP handler, in case we were aborted
112sub clear_status {
113  kill 15, $pid if $pid;
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;
119}
120
121$SIG{HUP} = \&clear_status;
122$SIG{TERM} = \&clear_status;
123$SIG{INT} = \&clear_status;
124
125# Read the metadata information from the file.
126my ($filepath) = $arguments{"file"};
127my ($fileinfo) = ImageInfo($filepath);
128my ($magic) = $fileinfo->{FileType};
129my ($tempdir);
130my ($newpath);
131
132if ($magic) {
133  # $magic means that Image::ExifTool was able to identify the type of file
134  printf(ZEPHYR "%s file %s\n", $magic, $arguments{"job-title"});
135  $status .= sprintf(" Filetype: %s.", $magic);
136  $status .= sprintf(" Filename: %s.", $arguments{"job-title"});
137
138  if (exists $fileinfo->{'Title'}) {
139    printf(ZEPHYR "\@b{%s}\n", $fileinfo->{'Title'}) if exists $fileinfo->{'Title'};
140    $status .= sprintf(" Title: %s.", $fileinfo->{'Title'});
141  }
142  foreach my $key (qw/Artist Album AlbumArtist/) {
143    if (exists $fileinfo->{$key}) {
144      printf(ZEPHYR "%s\n", $fileinfo->{$key}) if exists $fileinfo->{$key};
145      $status .= sprintf(" %s: %s\n", $key, $fileinfo->{$key});
146    }
147  }
148
149  $tempdir = tempdir();
150  #awful hack -- geofft
151  #== -- quentin
152  # This code appears to create a new temporary directory and symlink
153  # the job file into the temporary directory under the original
154  # filename. I think this is because mplayer sometimes uses the file
155  # extension to identify a filetype.
156  $newpath = $tempdir . '/' . basename($arguments{"job-title"});
157  symlink($filepath, $newpath);
158  $filepath = $newpath;
159}
160elsif ($arguments{copies} == 42) {
161  # This is a flag that is set by jobs queued by split_playlist(); it tells us to not try to split the playlist again.
162  # Call resolve_external_reference to apply some heuristics to determine the filetype.
163  $filepath = resolve_external_reference($filepath, \%arguments);
164  if ($filepath =~ m|http://www\.youtube\.com/watch\?v=|) {
165    # YouTube URLs are resolved by the youtube-dl command.
166    # Launch youtube-dl
167    $pid = open(YTDL, "-|");
168    if ($pid) {
169        print ZEPHYR "YouTube video $filepath.\nCurrently downloading, please wait...";
170        close ZEPHYR;
171        while (<YTDL>) {
172            open(ZEPHYR, "|-", @zwrite_command);
173            print ZEPHYR $_;
174            close ZEPHYR;
175        }
176        open(ZEPHYR, "|-", @zwrite_command);
177        print ZEPHYR "Done downloading.";
178        close ZEPHYR;
179    }
180    else {
181        my @args = ("youtube-dl", "-q", "-o", "/tmp/youtube.flv", $filepath);
182        exec(@args) or die "Couldn't exec youtube-dl";
183    }
184
185    $filepath = "/tmp/youtube.flv";
186    # Print the title to zephyr and the status string.
187  } else { # Doesn't appear to be a YouTube URL.
188    print STDERR "Resolved external reference to $filepath\n";
189    printf(ZEPHYR "%s\n", $filepath);
190    $status .= sprintf(" External: %s\n", $filepath);
191  }
192}
193elsif (-T $filepath) { # If the file appears to be a text file, treat it as a playlist.
194  split_playlist($filepath, \%arguments);
195  close(ZEPHYR);
196  # See http://www.cups.org/documentation.php/api-filter.html#MESSAGES
197  print CUPS "NOTICE: $status\n";
198  exit 0;
199}
200
201close(ZEPHYR);
202print CUPS "NOTICE: $status\n";
203play_mplayer_audio($filepath, \%arguments);
204
205# Remove the symlink we made earlier for the filetype.
206if ($magic) {
207  unlink($newpath);
208  rmdir($tempdir);
209}
210
211# Play an external stream reference
212sub resolve_external_reference {
213  # Retrieve those command line opts.
214  my ($filepath, $arguments) = @_;
215
216  my ($format, $uri, $userpass);
217
218  open(FILE, "<", $filepath) or die "Couldn't open spool file";
219  if (<FILE> =~ /^(\S+)/) {
220    # Take the leading non-whitespace as a URL
221    $uri=$1;
222
223    if ($uri =~ m|http://www\.youtube\.com/watch\?v=|) {
224      return $uri;
225    }
226
227    # Fetch the URL with a HEAD request to get the content type
228    my $response = $ua->head($uri);
229
230    my $contenttype=($response->content_type() or "unknown");
231
232    if ($contenttype eq "audio/mpeg") { $format="MP3" }
233    elsif ($contenttype eq "application/x-ogg") { $format="OGG" }
234    elsif ($contenttype eq "application/ogg") { $format="OGG" }
235    elsif ($contenttype eq "audio/x-scpls") { $format="SHOUTCAST" }
236    else {
237      print ZEPHYR
238        "Unknown Content-Type $contenttype for URI $uri\n";
239    }
240  } else { # Unable to match the URL regex
241    print ZEPHYR "Couldn't read URI for external reference\n";
242    # Return the existing path, in the hopes that mplayer knows what to do with it.
243    return $filepath;
244  }
245
246  if ($format eq "SHOUTCAST") {
247    print ZEPHYR "Shoutcast playlist...\n";
248    return get_shoutcast($uri);
249  } elsif ($format eq "MP3") {
250  } elsif ($format eq "OGG") {
251  } else {
252    print ZEPHYR "Unrecognized stream format: $format\n";
253  }
254  return $uri;
255}
256
257sub split_playlist {
258  my ($file, $arguments) = @_;
259
260  my $i = 0;
261
262  open(FILE, "<", $filepath) or die "Couldn't open spool file";
263  while (<FILE>) {
264    chomp;
265    if (/^([^#]\S+)/) {
266      printf (STDERR "Found playlist line: %s\n", $_);
267      $ENV{CUPS_SERVER}='localhost';
268      open(LP, "|-", "lp", "-d", "$queue", "-n", "42"); #'-#', '42', '-J', $arguments->{"job-title"}, '-o', 'job-priority=100');
269      print LP $1;
270      close(LP);
271      $i++;
272    }
273  }
274  printf(ZEPHYR "Playlist containing %d valid entries, split into separate jobs.\n", $i);
275}
276
277# Process a Shoutcast playlist
278# get_shoutcast(URI)
279sub get_shoutcast {
280  my $uri = shift(@_);
281
282  my $response = $ua->get($uri);
283  my (@titles, @uris);
284
285  foreach (split("\n", $response->content())) {
286      if (/^File\d+=(\S+)/) {
287          push(@uris, $1);
288      }
289      if (/^Title\d+=(.+)$/) {
290          push(@titles, $1);
291      }
292  }
293
294  # choose a random server
295  my $server = int(rand scalar(@uris));
296  # print the name of the stream if available
297  print ZEPHYR "$titles[$server]\n";
298  return $uris[$server];
299}
300
301sub play_mplayer_audio {
302  my ($filepath, $opts) = @_;
303
304  # Open up a zwrite command to show the mplayer output
305  my @zwrite_command = (qw(/usr/bin/zwrite -d -n -c), $zephyr_class, "-i", $queue.'@'.$host, "-s", "Gutenbach Music Spooler");
306
307  print STDERR "Invoking (from play_mplayer_audio): @zwrite_command\n";
308
309  # fork for mplayer
310  $pid = open(MP3STATUS, "-|");
311  unless (defined $pid) {
312    open(ZEPHYR, "|-", @zwrite_command) or die "Couldn't launch zwrite: $!";
313    print ZEPHYR "Couldn't fork: $!\n";
314    close(ZEPHYR);
315    return;
316  }
317
318  if ($pid) { #parent
319    # Check if there were any errors
320    if ($_ = <MP3STATUS>) {
321      open(ZEPHYR, "|-", @zwrite_command) or die "Couldn't launch zwrite: $!";
322      print ZEPHYR "Playback completed with the following errors:\n";
323      while (<MP3STATUS>) {
324        print ZEPHYR $_;
325      }
326      close(ZEPHYR);
327    } else {
328      open(ZEPHYR, "|-", @zwrite_command) or die "Couldn't launch zwrite: $!";
329      print ZEPHYR "Playback completed successfully.\n";
330      close(ZEPHYR);
331    }
332    close(MP3STATUS) || print ZEPHYR "mplayer exited $?\n";
333  }
334  else { # child
335    # redirect STDERR to STDOUT
336    open STDERR, '>&STDOUT';
337    # make sure that mplayer doesn't try to intepret the file as keyboard input
338    close(STDIN);
339    open(STDIN, "/dev/null");
340
341    my @args = (qw|/usr/bin/mplayer -vo fbdev2 -zoom -x 1024 -y 768 -framedrop -nolirc -cache 512 -ao alsa -really-quiet |, $filepath);
342    #pint STDERR "About to exec: ", Dumper([@args]);
343    exec(@args) ||
344      die "Couldn't exec";
345  }
346}
Note: See TracBrowser for help on using the repository browser.