source: gutenbach/debian/lib/sipbmp3-filter @ f014bc4

debianmacno-cupsnodebathenaweb
Last change on this file since f014bc4 was f014bc4, checked in by Edward Z. Yang <edwardzyang@…>, 16 years ago

Clear status if lprm'ed.

Signed-off-by: Edward Z. Yang <edwardzyang@…>

  • Property mode set to 100755
File size: 8.0 KB
Line 
1#!/usr/athena/bin/perl
2# Play the data on STDIN as an audio file
3#
4# $Id: sipbmp3-filter,v 1.26 2009/02/20 00:27:17 geofft Exp root $
5# $Source: /usr/local/bin/RCS/sipbmp3-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 Image::ExifTool qw(ImageInfo);
18use File::Spec::Functions;
19use File::Temp qw{tempdir};
20use File::Basename qw(basename);
21use LWP::UserAgent;
22use Data::Dumper;
23
24my $zephyr_class = "sipb-auto";
25my $host = "zsr";
26
27# Configuration
28my $config_file = "/etc/sipbmp3-filter-config.pl";
29if (-r $config_file) {
30    # Inline the configuration file
31    local $/;
32    my $fh;
33    open $fh, $config_file;
34    eval <$fh>;
35}
36
37my $ua = new LWP::UserAgent;
38
39close(STDERR);
40open(STDERR, ">>", "/tmp/sipbmp3.log") or warn "Couldn't open log: $!";
41
42$ENV{"TERM"}="vt100";
43
44print STDERR "STDERR FROM SPOOL FILTER\n";
45
46# set real uid to be effective uid
47$< = $>;
48
49# Select the correct output device and set the volume
50#system("amixer -q set Headphone 100\% unmute");
51
52# The command line we get from lpd is (no spaces between options and args):
53#  -C lpr -C class
54#  -A LPRng internal identifier
55#  -H originating host
56#  -J lpr -J jobname (default: list of files)
57#  -L lpr -U username
58#  -P logname
59#  -Q queuename (lpr -Q)
60#  -Z random user-specified options
61#  -a printcap af (accounting file name)
62#  -d printcap sd entry (spool dir)
63#  -e print job data file name (currently being processed)
64#  -h print job originiating host (same as -H)
65#  -j job number in spool queue
66#  -k print job control file name
67#  -l printcap pl (page length)
68#  -n user name (same as -L)
69#  -s printcap sf (status file)
70#  -w printcap pw (page width)
71#  -x printcap px (page x dimension)
72#  -y printcap py (page y dimension)
73# accounting file name
74
75printf(STDERR "Got \@ARGV: %s\n", Dumper(\@ARGV));
76
77my %opts;
78
79my @NEWARGV;
80
81foreach my $arg (@ARGV) {
82  if ($arg =~ m/^-([a-zA-Z])(.*)$/) {
83    $opts{$1} = $2;
84  } else {
85    push @NEWARGV, @ARGV;
86  }
87}
88
89@ARGV = @NEWARGV;
90
91printf(STDERR Dumper(\%opts));
92
93# Status messages at start of playback
94open(ZEPHYR, '|/usr/athena/bin/zwrite -d -n -c '. $zephyr_class .' -i ' .
95  'sipbmp3@'.$host.' -s "SIPB LPR music spooler"');
96print(ZEPHYR "$opts{'n'}\@$opts{'H'} is playing:\n");
97
98# For the Now Playing remctl command
99open(STATUS, '>', '/var/run/sipbmp3/status') or die("Can't open status file /var/run/sipbmp3/status");
100
101# SIGHUP handler
102sub clear_status {
103    # Possible race condition if the previous status is still going
104    open(STA, '>', '/var/run/sipbmp3/status');
105    close(STA);
106    open(ZEPH, '|/usr/athena/bin/zwrite -d -n -c '. $zephyr_class .' -i '.
107        'sipbmp3@'.$host.' -s "SIPB LPR music spooler"');
108    print(ZEPH "Playback aborted.\n");
109    close(ZEPH);
110    die;
111}
112$SIG{HUP} = \&clear_status;
113
114# So, the file we're currently processing is "-d/-e".
115
116# Read the metadata information from the file.
117my ($filepath) = catfile($opts{'d'}, $opts{'e'});
118my ($fileinfo) = ImageInfo($filepath);
119my ($magic) = $fileinfo->{FileType};
120
121if ($magic) {
122    printf(ZEPHYR "%s file %s\n", $magic, $opts{'J'});
123    printf(STATUS "Filetype: %s\n", $magic);
124    printf(STATUS "Filename: %s\n", $opts{'J'});
125    if (exists $fileinfo->{'Title'}) {
126        printf(ZEPHYR "\@b{%s}\n", $fileinfo->{'Title'}) if exists $fileinfo->{'Title'};
127        printf(STATUS "Title: %s\n", $fileinfo->{'Title'});
128    }
129    foreach my $key (qw/Artist Album AlbumArtist/) {
130        if (exists $fileinfo->{$key}) {
131            printf(ZEPHYR "%s\n", $fileinfo->{$key}) if exists $fileinfo->{$key};
132            printf(STATUS "%s: %s\n", $key, $fileinfo->{$key});
133        }
134    }
135    my $tempdir = tempdir();
136    $opts{'J'} =~ s/_mp3/.mp3/; #awful hack -- geofft
137    my $newpath = $tempdir . '/' . basename($opts{'J'});
138    symlink($filepath, $newpath);
139    $filepath = $newpath;
140}
141elsif ($opts{'C'} eq 'Z') {
142    $filepath = resolve_external_reference($filepath, \%opts);
143    print STDERR "Resolved external reference to $filepath\n";
144    printf(ZEPHYR "%s\n", $filepath);
145    printf(STATUS "External: %s\n", $filepath);
146}
147elsif (-T $filepath) {
148    split_playlist($filepath, \%opts);
149    close(ZEPHYR);
150    close(STATUS);
151    exit 0;
152}
153
154#printf(STDERR "Job priority %s\n", $opts{'C'}) if $opts{'C'} eq 'Z';
155#printf(ZEPHYR "Job priority %s\n", $opts{'C'}) if ($opts{'C'} && ($opts{'C'} ne 'A'));
156close(ZEPHYR);
157close(STATUS);
158play_mplayer_audio($filepath, \%opts);
159
160if ($magic) {
161    unlink($newpath);
162    rmdir($tempdir);
163}
164
165# Play an external stream reference
166sub resolve_external_reference {
167    # Retrieve those command line opts.
168    my ($filepath, $opts) = @_;
169
170    my $format, $uri, $userpass;
171
172    if (<STDIN> =~ /^(\S+)/) {
173        $uri=$1;
174
175        my $response = $ua->head($uri);
176       
177        $contenttype=($response->content_type() or "unknown");
178       
179        if ($contenttype eq "audio/mpeg") { $format="MP3" }
180        elsif ($contenttype eq "application/x-ogg") { $format="OGG" }
181        elsif ($contenttype eq "application/ogg") { $format="OGG" }
182        elsif ($contenttype eq "audio/x-scpls") { $format="SHOUTCAST" }
183        else {
184            print ZEPHYR
185                "Unknown Content-Type $contenttype for URI $uri\n";
186        }
187    } else {
188        print ZEPHYR "Couldn't read URI for external reference\n";
189        return $filepath;
190    }
191
192    if ($format eq "SHOUTCAST") {
193        print ZEPHYR "Shoutcast playlist...\n";
194        #Don't close ZEPHYR yet, will print the name of the stream if available
195        return &get_shoutcast($uri);
196    } elsif ($format eq "MP3") {
197    } elsif ($format eq "OGG") {
198    } else {
199      print ZEPHYR "Unrecognized stream format: $format\n";
200    }
201    return $uri;
202}
203
204sub split_playlist {
205    my ($file, $opts) = @_;
206
207    my $i = 0;
208   
209    while (<STDIN>) {
210        chomp;
211        if (/^([^#]\S+)/) {
212            printf (STDERR "Found line: %s\n", $_);
213            open(LPR, "|-", qw/mit-lpr -Psipbmp3@localhost -CZ/, '-J'.$opts->{J});
214            print LPR $1;
215            close(LPR);
216        $i++;
217        }
218    }
219    printf(ZEPHYR "Playlist containing %d valid entries, split into separate jobs.\n", $i);
220}
221
222# Process a Shoutcast playlist
223# get_shoutcast(URI)
224sub get_shoutcast {
225  my $uri = shift(@_);
226 
227  my $response = $ua->get($uri);
228
229  foreach (split("\n", $response->content())) {
230      if (/^File\d+=(\S+)/) {
231          push(@uris, $1);
232      }
233      if (/^Title\d+=(.+)$/) {
234          push(@titles, $1);
235      }
236  }
237 
238  # choose a random server
239  $server = int(rand scalar(@uris));
240  # print the name of the stream if available
241  print ZEPHYR "$titles[$server]\n";
242  return $uris[$server];
243}
244
245sub play_mplayer_audio {
246    my ($filepath, $opts) = @_;
247
248    # Prepare to write status:
249    open(ZEPHYR, '|/usr/athena/bin/zwrite -d -n -c '.$zephyr_class.' -i ' .
250         'sipbmp3@'.$host.' -s "SIPB LPR music spooler"');
251   
252    # fork for mpg123
253    my $pid = open(MP3STATUS, "-|");
254    unless (defined $pid) {
255        print ZEPHYR "Couldn't fork: $!\n";
256        close(ZEPHYR);
257        return;
258    }
259   
260    if ($pid) { #parent
261        # Check if there were any errors
262        if ($_ = <MP3STATUS>) {
263            print ZEPHYR "Playback completed with the following errors:\n";
264            print ZEPHYR $_;
265            while (<MP3STATUS>) {
266                print ZEPHYR $_;
267            }
268        } else {
269            print ZEPHYR "Playback completed successfully.\n";
270        }
271        close(MP3STATUS) || print ZEPHYR "mplayer exited $?\n";
272       
273        close(ZEPHYR);
274        open(STATUS, '>', '/var/run/sipbmp3/status');
275        close(STATUS);
276    }
277  else { # child
278      # redirect STDERR to STDOUT
279      open STDERR, '>&STDOUT';
280      # make sure that mplayer doesn't try to intepret the file as keyboard input
281      close(STDIN);
282      open(STDIN, "/dev/null");
283      #print STDERR Dumper([qw|/usr/bin/mplayer -nolirc -ao alsa -quiet|, $filepath]);
284      my @args = (qw|/usr/bin/mplayer -vo null -nolirc -ao alsa -cache 512 -really-quiet|, $filepath);
285      #print STDERR "About to exec: ", Dumper([@args]);
286      exec(@args) ||
287          die "Couldn't exec";
288  }
289}
290
291# ID3 comments often have useless crap because tools like iTunes were
292# written by drooling idiots
293sub filter_comment {
294  my $comment = shift(@_);
295
296  if ($comment =~ /^engiTunes_CDDB/) {
297    return undef;
298  }
299  return $comment;
300}
301
302
Note: See TracBrowser for help on using the repository browser.