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

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

Implement status file for remctl.
Signed-off-by: Edward Z. Yang <edwardzyang@…>

  • Property mode set to 100755
File size: 7.7 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# So, the file we're currently processing is "-d/-e".
102
103# Read the metadata information from the file.
104my ($filepath) = catfile($opts{'d'}, $opts{'e'});
105my ($fileinfo) = ImageInfo($filepath);
106my ($magic) = $fileinfo->{FileType};
107
108if ($magic) {
109    printf(ZEPHYR "%s file %s\n", $magic, $opts{'J'});
110    printf(STATUS "Filetype: %s\n", $magic);
111    printf(STATUS "Filename: %s\n", $opts{'J'});
112    if (exists $fileinfo->{'Title'}) {
113        printf(ZEPHYR "\@b{%s}\n", $fileinfo->{'Title'}) if exists $fileinfo->{'Title'};
114        printf(STATUS "Title: %s\n", $fileinfo->{'Title'});
115    }
116    foreach my $key (qw/Artist Album AlbumArtist/) {
117        if (exists $fileinfo->{$key}) {
118            printf(ZEPHYR "%s\n", $fileinfo->{$key}) if exists $fileinfo->{$key};
119            printf(STATUS "%s: %s\n", $key, $fileinfo->{$key});
120        }
121    }
122    my $tempdir = tempdir();
123    $opts{'J'} =~ s/_mp3/.mp3/; #awful hack -- geofft
124    my $newpath = $tempdir . '/' . basename($opts{'J'});
125    symlink($filepath, $newpath);
126    $filepath = $newpath;
127}
128elsif ($opts{'C'} eq 'Z') {
129    $filepath = resolve_external_reference($filepath, \%opts);
130    print STDERR "Resolved external reference to $filepath\n";
131    printf(ZEPHYR "%s\n", $filepath);
132    printf(STATUS "External: %s\n", $filepath);
133}
134elsif (-T $filepath) {
135    split_playlist($filepath, \%opts);
136    close(ZEPHYR);
137    close(STATUS);
138    exit 0;
139}
140
141#printf(STDERR "Job priority %s\n", $opts{'C'}) if $opts{'C'} eq 'Z';
142#printf(ZEPHYR "Job priority %s\n", $opts{'C'}) if ($opts{'C'} && ($opts{'C'} ne 'A'));
143close(ZEPHYR);
144close(STATUS);
145play_mplayer_audio($filepath, \%opts);
146
147if ($magic) {
148    unlink($newpath);
149    rmdir($tempdir);
150}
151
152# Play an external stream reference
153sub resolve_external_reference {
154    # Retrieve those command line opts.
155    my ($filepath, $opts) = @_;
156
157    my $format, $uri, $userpass;
158
159    if (<STDIN> =~ /^(\S+)/) {
160        $uri=$1;
161
162        my $response = $ua->head($uri);
163       
164        $contenttype=($response->content_type() or "unknown");
165       
166        if ($contenttype eq "audio/mpeg") { $format="MP3" }
167        elsif ($contenttype eq "application/x-ogg") { $format="OGG" }
168        elsif ($contenttype eq "application/ogg") { $format="OGG" }
169        elsif ($contenttype eq "audio/x-scpls") { $format="SHOUTCAST" }
170        else {
171            print ZEPHYR
172                "Unknown Content-Type $contenttype for URI $uri\n";
173        }
174    } else {
175        print ZEPHYR "Couldn't read URI for external reference\n";
176        return $filepath;
177    }
178
179    if ($format eq "SHOUTCAST") {
180        print ZEPHYR "Shoutcast playlist...\n";
181        #Don't close ZEPHYR yet, will print the name of the stream if available
182        return &get_shoutcast($uri);
183    } elsif ($format eq "MP3") {
184    } elsif ($format eq "OGG") {
185    } else {
186      print ZEPHYR "Unrecognized stream format: $format\n";
187    }
188    return $uri;
189}
190
191sub split_playlist {
192    my ($file, $opts) = @_;
193
194    my $i = 0;
195   
196    while (<STDIN>) {
197        chomp;
198        if (/^([^#]\S+)/) {
199            printf (STDERR "Found line: %s\n", $_);
200            open(LPR, "|-", qw/mit-lpr -Psipbmp3@localhost -CZ/, '-J'.$opts->{J});
201            print LPR $1;
202            close(LPR);
203        $i++;
204        }
205    }
206    printf(ZEPHYR "Playlist containing %d valid entries, split into separate jobs.\n", $i);
207}
208
209# Process a Shoutcast playlist
210# get_shoutcast(URI)
211sub get_shoutcast {
212  my $uri = shift(@_);
213 
214  my $response = $ua->get($uri);
215
216  foreach (split("\n", $response->content())) {
217      if (/^File\d+=(\S+)/) {
218          push(@uris, $1);
219      }
220      if (/^Title\d+=(.+)$/) {
221          push(@titles, $1);
222      }
223  }
224 
225  # choose a random server
226  $server = int(rand scalar(@uris));
227  # print the name of the stream if available
228  print ZEPHYR "$titles[$server]\n";
229  return $uris[$server];
230}
231
232sub play_mplayer_audio {
233    my ($filepath, $opts) = @_;
234
235    # Prepare to write status:
236    open(ZEPHYR, '|/usr/athena/bin/zwrite -d -n -c '.$zephyr_class.' -i ' .
237         'sipbmp3@'.$host.' -s "SIPB LPR music spooler"');
238   
239    # fork for mpg123
240    my $pid = open(MP3STATUS, "-|");
241    unless (defined $pid) {
242        print ZEPHYR "Couldn't fork: $!\n";
243        close(ZEPHYR);
244        return;
245    }
246   
247    if ($pid) { #parent
248        # Check if there were any errors
249        if ($_ = <MP3STATUS>) {
250            print ZEPHYR "Playback completed with the following errors:\n";
251            print ZEPHYR $_;
252            while (<MP3STATUS>) {
253                print ZEPHYR $_;
254            }
255        } else {
256            print ZEPHYR "Playback completed successfully.\n";
257        }
258        close(MP3STATUS) || print ZEPHYR "mplayer exited $?\n";
259       
260        close(ZEPHYR);
261        open(STATUS, '>', '/var/run/sipbmp3/status');
262        close(STATUS);
263    }
264  else { # child
265      # redirect STDERR to STDOUT
266      open STDERR, '>&STDOUT';
267      # make sure that mplayer doesn't try to intepret the file as keyboard input
268      close(STDIN);
269      open(STDIN, "/dev/null");
270      #print STDERR Dumper([qw|/usr/bin/mplayer -nolirc -ao alsa -quiet|, $filepath]);
271      my @args = (qw|/usr/bin/mplayer -vo null -nolirc -ao alsa -cache 512 -really-quiet|, $filepath);
272      #print STDERR "About to exec: ", Dumper([@args]);
273      exec(@args) ||
274          die "Couldn't exec";
275  }
276}
277
278# ID3 comments often have useless crap because tools like iTunes were
279# written by drooling idiots
280sub filter_comment {
281  my $comment = shift(@_);
282
283  if ($comment =~ /^engiTunes_CDDB/) {
284    return undef;
285  }
286  return $comment;
287}
288
289
Note: See TracBrowser for help on using the repository browser.