source: gutenbach/debian/lib/gutenbach @ 509c1f6

nodebathena
Last change on this file since 509c1f6 was 509c1f6, checked in by Jessica B. Hamrick <jhamrick@…>, 14 years ago

Move gutenbach package files into a subfolder

  • Property mode set to 100755
File size: 8.5 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/ $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
97
98my $status;
99if (exists($arguments{"options"}{"job-originating-host-name"})) {
100   
101    $status = "User: ".$arguments{"user"}."\@".$arguments{"options"}{"job-originating-host-name"};
102} else {
103   
104    $status = "User: ".$arguments{"user"};
105}
106
107# SIGHUP handler, in case we were aborted
108sub clear_status {
109  kill 15, $pid if $pid;
110  die;
111}
112
113$SIG{HUP} = \&clear_status;
114$SIG{TERM} = \&clear_status;
115
116# Read the metadata information from the file.
117my ($filepath) = $arguments{"file"};
118my ($fileinfo) = ImageInfo($filepath);
119my ($magic) = $fileinfo->{FileType};
120my ($tempdir);
121my ($newpath);
122
123if ($magic) {
124  # $magic means that Image::ExifTool was able to identify the type of file
125  $status .= sprintf(" Filetype: %s.", $magic);
126  $status .= sprintf(" Filename: %s.", $arguments{"job-title"});
127
128  if (exists $fileinfo->{'Title'}) {
129   
130    $status .= sprintf(" Title: %s.", $fileinfo->{'Title'});
131  }
132  foreach my $key (qw/Artist Album AlbumArtist/) {
133    if (exists $fileinfo->{$key}) {
134     
135      $status .= sprintf(" %s: %s\n", $key, $fileinfo->{$key});
136    }
137  }
138
139  $tempdir = tempdir();
140  #awful hack -- geofft
141  #== -- quentin
142  # This code appears to create a new temporary directory and symlink
143  # the job file into the temporary directory under the original
144  # filename. I think this is because mplayer sometimes uses the file
145  # extension to identify a filetype.
146  $newpath = $tempdir . '/' . basename($arguments{"job-title"});
147  symlink($filepath, $newpath);
148  $filepath = $newpath;
149}
150elsif ($arguments{copies} == 42) {
151  # This is a flag that is set by jobs queued by split_playlist(); it tells us to not try to split the playlist again.
152  # Call resolve_external_reference to apply some heuristics to determine the filetype.
153  $filepath = resolve_external_reference($filepath, \%arguments);
154  if ($filepath =~ m|http://www\.youtube\.com/watch\?v=|) {
155    # YouTube URLs are resolved by the youtube-dl command.
156    # Launch youtube-dl
157    open(YTDL, "-|", "youtube-dl", "-g", $filepath) or die "Unable to invoke youtube-dl";
158    # Read the title (currently not doing so because youtube-dl doesn't know how to get the title.
159    my $title = ""; # <YTDL>
160    # Print the title to the status string.
161   
162    $status .= " YouTube video $filepath. $title.";
163    # youtube-dl prints the URL of the flash video, which we pass to mplayer as a filename.
164    $filepath = <YTDL>;
165    chomp $filepath;
166  } else { # Doesn't appear to be a YouTube URL.
167    print STDERR "Resolved external reference to $filepath\n";
168   
169    $status .= sprintf(" External: %s\n", $filepath);
170  }
171}
172elsif (-T $filepath) { # If the file appears to be a text file, treat it as a playlist.
173  split_playlist($filepath, \%arguments);
174 
175  # See http://www.cups.org/documentation.php/api-filter.html#MESSAGES
176  print CUPS "NOTICE: $status\n";
177  exit 0;
178}
179
180
181print CUPS "NOTICE: $status\n";
182play_mplayer_audio($filepath, \%arguments);
183
184# Remove the symlink we made earlier for the filetype.
185if ($magic) {
186  unlink($newpath);
187  rmdir($tempdir);
188}
189
190# Play an external stream reference
191sub resolve_external_reference {
192  # Retrieve those command line opts.
193  my ($filepath, $arguments) = @_;
194
195  my ($format, $uri, $userpass);
196
197  open(FILE, "<", $filepath) or die "Couldn't open spool file";
198  if (<FILE> =~ /^(\S+)/) {
199    # Take the leading non-whitespace as a URL
200    $uri=$1;
201
202    if ($uri =~ m|http://www\.youtube\.com/watch\?v=|) {
203      return $uri;
204    }
205
206    # Fetch the URL with a HEAD request to get the content type
207    my $response = $ua->head($uri);
208
209    my $contenttype=($response->content_type() or "unknown");
210
211    if ($contenttype eq "audio/mpeg") { $format="MP3" }
212    elsif ($contenttype eq "application/x-ogg") { $format="OGG" }
213    elsif ($contenttype eq "application/ogg") { $format="OGG" }
214    elsif ($contenttype eq "audio/x-scpls") { $format="SHOUTCAST" }
215    else {
216   
217    }
218  } else { # Unable to match the URL regex
219   
220    # Return the existing path, in the hopes that mplayer knows what to do with it.
221    return $filepath;
222  }
223
224  if ($format eq "SHOUTCAST") {
225   
226    return get_shoutcast($uri);
227  } elsif ($format eq "MP3") {
228  } elsif ($format eq "OGG") {
229  } else {
230   
231  }
232  return $uri;
233}
234
235sub split_playlist {
236  my ($file, $arguments) = @_;
237
238  my $i = 0;
239
240  open(FILE, "<", $filepath) or die "Couldn't open spool file";
241  while (<FILE>) {
242    chomp;
243    if (/^([^#]\S+)/) {
244      printf (STDERR "Found playlist line: %s\n", $_);
245      open(LPR, "|-", 'lpr', '-P'.$queue.'@localhost', '-#', '42', '-J', $arguments->{"job-title"}, '-o', 'job-priority=100');
246      print LPR $1;
247      close(LPR);
248      $i++;
249    }
250  }
251 
252}
253
254# Process a Shoutcast playlist
255# get_shoutcast(URI)
256sub get_shoutcast {
257  my $uri = shift(@_);
258
259  my $response = $ua->get($uri);
260  my (@titles, @uris);
261
262  foreach (split("\n", $response->content())) {
263      if (/^File\d+=(\S+)/) {
264          push(@uris, $1);
265      }
266      if (/^Title\d+=(.+)$/) {
267          push(@titles, $1);
268      }
269  }
270
271  # choose a random server
272  my $server = int(rand scalar(@uris));
273  # print the name of the stream if available
274 
275  return $uris[$server];
276}
277
278sub play_mplayer_audio {
279  my ($filepath, $opts) = @_;
280
281
282  # fork for mplayer
283  $pid = open(MP3STATUS, "-|");
284  unless (defined $pid) {
285    return;
286  }
287
288  if ($pid) { #parent
289    # Check if there were any errors
290    if ($_ = <MP3STATUS>) {
291     
292      while (<MP3STATUS>) {
293       
294      }
295     
296    } else {
297     
298    }
299    close(MP3STATUS);
300  }
301  else { # child
302    # redirect STDERR to STDOUT
303    open STDERR, '>&STDOUT';
304    # make sure that mplayer doesn't try to intepret the file as keyboard input
305    close(STDIN);
306    open(STDIN, "/dev/null");
307
308    my @args = (qw|/usr/bin/mplayer -vo fbdev2 -zoom -x 1024 -y 768 -framedrop -nolirc -cache 512 -ao alsa -really-quiet |, $filepath);
309    #print STDERR "About to exec: ", Dumper([@args]);
310    exec(@args) ||
311      die "Couldn't exec";
312  }
313}
Note: See TracBrowser for help on using the repository browser.