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

debianmacno-cupsnodebathenaweb
Last change on this file since bc5ca87 was bc5ca87, checked in by jhawk <jhawk>, 21 years ago

Punt some debugging, list URI in failure message.

  • Property mode set to 100755
File size: 15.8 KB
Line 
1#!/usr/athena/bin/perl
2# Play the data on STDIN as an audio file
3#
4# $Id: sipbmp3-filter,v 1.8 2003-08-11 02:11:28 jhawk Exp $
5# $Source: /tmp/tmp.UFBNno9997/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
16use Getopt::Std;
17
18# Get the MP3Info module from this directory, because I suck.
19unshift(@INC, "/usr/local/bin");
20require MP3::Info;
21import MP3::Info;
22&use_winamp_genres();
23
24print STDERR "STDERR FROM SPOOL FILTER\n";
25
26# set real uid to be effective uid
27$< = $>;
28
29# Attach necessary lockers
30system("/bin/athena/attach -h -n -q infoagents sipb outland consult 2>&1 > /dev/null");
31
32# Select the correct output device and set the volume
33system("/usr/local/bin/audio_setdevice -out headphones 100 2>&1 </dev/null > /dev/null");
34
35# The command line we get from lpd is (no spaces between options and args):
36#  -C lpr -C class
37#  -A LPRng internal identifier
38#  -H originating host
39#  -J lpr -J jobname (default: list of files)
40#  -L lpr -U username
41#  -P logname
42#  -Q queuename (lpr -Q)
43#  -a printcap af (accounting file name)
44#  -d printcap sd entry (spool dir)
45#  -e print job data file name (currently being processed)
46#  -h print job originiating host (same as -H)
47#  -j job number in spool queue
48#  -k print job control file name
49#  -l printcap pl (page length)
50#  -n user name (same as -L)
51#  -s printcap sf (status file)
52#  -w printcap pw (page width)
53#  -x printcap px (page x dimension)
54#  -y printcap py (page y dimension)
55# accounting file name
56
57# All the filter_options from lpd
58getopt('ACFHJLPQRZacdefhijklnprswxy', \%opts);
59
60# Status messages at start of playback
61open(ZEPHYR, '|/usr/athena/bin/zwrite -d -n -c sipb-auto -i sipbmp3@xcb -s "SIPB LPR music spooler"');
62print(ZEPHYR "User $opts{'n'} on host $opts{'H'} is playing:\n");
63
64# So, the file we're currently processing is "-d/-e".
65# Do some magic to make sure it's an MP3, and get the important bits
66# to zephyr out.
67open(DATAFILE, "$opts{'d'}/$opts{'e'}");
68sysread(DATAFILE, $magic, 3);
69close(DATAFILE);
70
71# MPEG header is beshort &0xffe0
72# meditate upon the header:
73($magic0, $magic1, @magic2) = unpack("C3", $magic);
74if ((($magic0 & 0xff) == 0xff) &&
75    (($magic1 & 0xe0) == 0xe0)) {
76  # MPEG audio file, we like it
77  # Fall through
78} elsif ($magic eq "ID3") {
79  # ID3 v2 does sketchy things with "garbage" beginning with ID3 at file start.
80  # MPEG audio file with ID3 tag, we like it
81  # Fall through
82} elsif ($magic eq "EXT") {
83  # This is an external stream reference (a jered-special)
84  &play_external_reference(\%opts, $magic);
85  exit 0;
86} elsif ($magic eq "htt") {
87  # This is an external stream reference (a jered-special)
88  &play_external_reference(\%opts, $magic);
89  exit 0;
90} elsif ($magic eq "Ogg") {
91  # Ogg-Vorbis audio file
92  &play_ogg_audio(\%opts);
93  exit 0;
94} else {
95    # add more cases later, whine for now
96    printf(ZEPHYR "I don't think this is an MPEG audio file... %02x %02x\n",
97           $magic0, $magic1);
98    print ZEPHYR "I'm going to try playing it as one anyway.\n";
99}
100# Default
101&play_mpeg_audio(\%opts);
102
103
104# Play an external stream reference
105sub play_external_reference {
106    # Retrieve those command line opts.
107    my %opts = %{shift(@_)};
108    my $magic = shift(@_);
109
110    # External references are *not* playlists; they only support
111    # a single URL in order to be fair.  A reference is structured as
112    # follows:
113    #
114    # EXT <format>\n
115    # <URI>[ <user:pass>]\n
116    # Descriptive text of the file that will be\n
117    # played; this may span multiple lines until the\n
118    # EOF
119    #
120    # Where <URI> is a valid URI for the stream, and <format> is a
121    # recognized format name (currently 'MP3' or 'OGG'). <user:pass>
122    # is an optional user and password pair for HTTP Basic Auth.
123    my $format, $uri, $userpass;
124
125    if ("$magic" eq "EXT") {
126      if (<STDIN> =~ /^EXT (.*)$/) {
127        # Found the header
128        $format = $1;
129      } else {
130        print ZEPHYR "Couldn't read EXT header\n";
131        close(ZEPHYR);
132      }
133 
134      if (<STDIN> =~ /^(\S*)\s*(.*)$/) {
135        # Found the URI (and optionally user:pass)
136        $uri = $1;
137        if ($2) {
138        $userpass = $2;
139        }
140      } else {
141        print ZEPHYR "Couldn't read URI for external reference\n";
142        close(ZEPHYR);
143      }
144  } elsif ("$magic" eq "htt") {
145      if (<STDIN> =~ /^(\S*)\s*(.*)$/) {
146          $uri=$1;
147          open(W3M, "/mit/sipb/bin/w3m -dump_head $uri|");
148          $contenttype="unknown";
149          while (<W3M>) {
150              if ($_ =~ /^Content-Type:\s(\S*)/) {
151                  $contenttype=$1;
152              }
153          }
154             if ($contenttype eq "audio/mpeg") { $format="MP3" }
155          elsif ($contenttype eq "application/x-ogg") { $format="OGG" }
156          elsif ($contenttype eq "application/ogg") { $format="OGG" }
157          else {
158              print ZEPHYR "Unknown Content-Type $contenttype for URI $uri\n";
159              close(ZEPHYR);
160          }
161      } else {
162        print ZEPHYR "Couldn't read URI for external reference\n";
163        close(ZEPHYR);
164      }
165  } else {
166      print ZEPHYR "Unknown syntax in play_external_reference(): $magic\n";
167      close(ZEPHYR);
168  }
169
170    # Echo the rest to the zephyr
171    while (<STDIN>) {
172      print ZEPHYR $_;
173    }
174    print ZEPHYR "\n";
175
176    # Play the thing the right way
177    if (($format eq "MP3") ||
178        ($format eq "mp3")) {
179      print ZEPHYR "Playing MP3 audio stream...\n";
180      close(ZEPHYR);
181      &play_mpeg_stream($uri, $userpass);
182    } elsif (($format eq "OGG") ||
183             ($format eq "ogg")) {
184      print ZEPHYR "Playing OggVorbis audio stream...\n";
185      close(ZEPHYR);
186      &play_ogg_stream($uri, $userpass);
187    } else {
188      print ZEPHYR "Unrecognized stream format: $format\n";
189      close(ZEPHYR);
190    }
191}
192
193
194# Play an MPEG audio stream
195# play_mpeg_stream(URI, userpass)
196sub play_mpeg_stream {
197  my $uri = shift(@_);
198  my $userpass = shift(@_);
199
200  # Add the user:pass argument if is was given to us
201  my $up = '';
202  if ($userpass) {
203    $up = '-u ' . $userpass;
204  }
205
206  system("ps ax | grep ogg123 | awk '{print $2}' | xargs kill -9");
207  system("ps ax | grep mpg123 | awk '{print $2}' | xargs kill -9");
208  system("chmod a+rw /dev/audio");
209  system("/mit/infoagents/bin/mpg123 -b 16384 -q $up $uri >/tmp/mpg123.out 2>&1");
210
211  # Done. Status:
212  open(ZEPHYR, '|/usr/athena/bin/zwrite -d -n -c sipb-auto -i sipbmp3@xcb -s "SIPB LPR music spooler"');
213
214  # Check if there were any errors
215  open(MP3STATUS, "/tmp/mpg123.out");
216  if ($_ = <MP3STATUS>) {
217    print ZEPHYR "Playback completed with the following errors:\n";
218    print ZEPHYR $_;
219    while (<MP3STATUS>) {
220      print ZEPHYR $_;
221    }
222  } else {
223    print ZEPHYR "Playback completed successfully.\n";
224  }
225  close(MP3STATUS);
226  unlink(MP3STATUS);
227
228  close(ZEPHYR);
229}
230
231# ID3 comments often have useless crap because tools like iTunes were
232# written by drooling idiots
233sub filter_comment {
234  my $comment = shift(@_);
235
236  if ($comment =~ /^engiTunes_CDDB/) {
237    return undef;
238  }
239  return $comment;
240}
241
242
243# Play an MPEG audio file
244sub play_mpeg_audio {
245    # Retrieve those command line opts.
246    my %opts = %{shift(@_)};
247
248    my %MPEGModes = ( 0 => "stereo",
249                      1 => "joint-stereo",
250                      2 => "dual-channel",
251                      3 => "single-channel");
252
253    # If it's an MP3 file, try to extract useful data
254    my $tag = get_mp3tag("$opts{'d'}/$opts{'e'}");
255    if (!$tag) {
256        print ZEPHYR "No ID3 tag found\n";
257        my @fnamearray = split /,/, $opts{'J'};
258        foreach $fname (@fnamearray) {
259            print ZEPHYR "Filename: $fname\n";
260        }
261#           print ZEPHYR "Filename: $opts{'J'}\n\n";
262    } else {
263      print ZEPHYR "Title          : $tag->{TITLE}\n";
264      print ZEPHYR "Artist         : $tag->{ARTIST}\n";
265      print ZEPHYR "Album          : $tag->{ALBUM}\n";
266      if ($tag->{TRACKNUM} =~ /(.*)\/.*/) {
267          $tag->{TRACKNUM} = $1;
268      }
269      if ($tag->{TRACKNUM}) {
270          print ZEPHYR "Track #        : $tag->{TRACKNUM}\n";
271      }
272      if ($tag->{YEAR}) {
273        print ZEPHYR "Year           : $tag->{YEAR}\n";
274      }
275      if ($tag->{GENRE}) {
276        # iTunes (?) does something weird with genres, leaving them
277        # as the string "(##)" where ## is the genre type. Let's deal
278        # with this.
279        if ($tag->{GENRE} =~ /^\((\d*)\)$/) {
280          $tag->{GENRE} = $MP3::Info::mp3_genres[$1];
281        }
282        if ($tag->{GENRE} =~ /^(\d*)$/) {
283          $tag->{GENRE} = $MP3::Info::mp3_genres[$1];
284        }
285        print ZEPHYR "Genre          : $tag->{GENRE}\n";
286      }
287      if (ref $tag->{COMMENT} eq 'ARRAY') {
288        foreach $index (0 .. $#{$tag->{COMMENT}}) {
289          if ($comment = filter_comment(@{$tag->{COMMENT}}[$index])) {
290            print ZEPHYR "Comment        : $comment\n";
291          }
292        }
293      } elsif ($tag->{COMMENT}) {
294        if ($comment = filter_comment($tag->{COMMENT})) {
295          print ZEPHYR "Comment        : $comment\n";
296        }
297      }
298
299      # Maybe get some extended ID3v2 info?
300      my $v2tag = get_mp3tag("$opts{'d'}/$opts{'e'}", 2, 1);
301      %lessinfo = %$v2tag;
302      foreach $dtag (keys %MP3::Info::v2_to_v1_names) {
303        delete $lessinfo{$dtag};
304      }
305      delete $lessinfo{'GENRE'};
306      # Delete annoying useless crap
307      my @bad_tags = ('GEO', 'GEOB', # General encapsulated object
308                      'PIC', 'APIC', # Attached picture.
309                      );
310      foreach $dtag (@bad_tags) {
311          delete $lessinfo{$dtag};
312      }
313      while (($key,$val) = each %lessinfo) {
314        printf ZEPHYR "%-15s: %s\n", $MP3::Info::v2_tag_names{$key}, $val;
315      }
316      print ZEPHYR "\n";
317    }
318
319    my $info = get_mp3info("$opts{'d'}/$opts{'e'}");
320    if (!$info) {
321        print ZEPHYR "No MPEG header found\n";
322    } else {
323        print ZEPHYR "MPEG $info->{VERSION} layer $info->{LAYER}, ";
324        if ($info->{VBR}) {
325            print ZEPHYR "VBR ";
326        }
327        print ZEPHYR "$info->{BITRATE} kbit/s, $info->{FREQUENCY} kHz ";
328        print ZEPHYR $MPEGModes{$info->{STEREO}};
329        print ZEPHYR "\n\n";
330        printf ZEPHYR "Track length: %d:%02ds\n", $info->{MM}, $info->{SS};
331    }
332    close(ZEPHYR);
333
334    # Play the file
335    # mpg123 is a crock.  If you don't give it -q, it needs to be on a pty
336    # or it SEGVs. Really.
337
338    system("chmod a+rw /dev/audio");
339    system("ps ax | grep ogg123 | awk '{print $2}' | xargs kill -9");
340    system("ps ax | grep mpg123 | awk '{print $2}' | xargs kill -9");
341    system("/mit/infoagents/bin/mpg123 -b 16384 -q - >/tmp/mpg123.out 2>&1");
342
343    # Done. Status:
344    open(ZEPHYR, '|/usr/athena/bin/zwrite -d -n -c sipb-auto -i sipbmp3@xcb -s "SIPB LPR music spooler"');
345
346    # Check if there were any errors
347    open(MP3STATUS, "/tmp/mpg123.out");
348    if ($_ = <MP3STATUS>) {
349        print ZEPHYR "Playback completed with the following errors:\n";
350        print ZEPHYR $_;
351        while (<MP3STATUS>) {
352            print ZEPHYR $_;
353        }
354    } else {
355        print ZEPHYR "Playback completed successfully.\n";
356        # Repeat tag data for those playing at home
357        if (!$tag) {
358          print ZEPHYR "No ID3 tag found\n";
359          print ZEPHYR "Filename: $opts{'J'}\n\n";
360        } else {
361          print ZEPHYR "Title          : $tag->{TITLE}\n";
362          print ZEPHYR "Artist         : $tag->{ARTIST}\n";
363          print ZEPHYR "Album          : $tag->{ALBUM}\n";
364          if ($tag->{TRACKNUM} =~ /(.*)\/.*/) {
365              $tag->{TRACKNUM} = $1;
366          }
367          if ($tag->{TRACKNUM}) {
368              print ZEPHYR "Track #        : $tag->{TRACKNUM}\n";
369          }
370          if ($tag->{YEAR}) {
371            print ZEPHYR "Year           : $tag->{YEAR}\n";
372          }
373          if ($tag->{GENRE}) {
374              print ZEPHYR "Genre          : $tag->{GENRE}\n";
375          }
376          if (ref $tag->{COMMENT} eq 'ARRAY') {
377            foreach $index (0 .. $#{$tag->{COMMENT}}) {
378              if ($comment = filter_comment(@{$tag->{COMMENT}}[$index])) {
379                print ZEPHYR "Comment        : $comment\n";
380              }
381            }
382          } elsif ($tag->{COMMENT}) {
383            if ($comment = filter_comment($tag->{COMMENT})) {
384              print ZEPHYR "Comment        : $comment\n";
385            }
386          }
387
388          # others
389          while (($key,$val) = each %lessinfo) {
390            printf ZEPHYR "%-15s: %s\n", $MP3::Info::v2_tag_names{$key}, $val;
391          }
392        }
393    }
394    close(MP3STATUS);
395    unlink(MP3STATUS);
396
397    close(ZEPHYR);
398}
399
400# Play an OggVorbis audio stream (doesn't support auth!)
401# play_ogg_stream(URI, userpass)
402sub play_ogg_stream {
403  my $uri = shift(@_);
404  my $userpass = shift(@_);
405
406  system("chmod a+rw /dev/audio");
407  system("ps -aef | grep ogg123 | awk '{print $2}' | xargs kill -9");
408  system("ps -aef | grep mpg123 | awk '{print $2}' | xargs kill -9");
409  system("/mit/sipb/bin/ogg123 -b 40000 -dau -q -f - $uri 2> /tmp/ogg123.out | audioplay");
410
411  # Done. Status:
412  open(ZEPHYR, '|/usr/athena/bin/zwrite -d -n -c sipb-auto -i sipbmp3@xcb -s "SIPB LPR music spooler"');
413
414  # Check if there were any errors
415  open(OGGSTATUS, "/tmp/ogg123.out");
416  if ($_ = <OGGSTATUS>) {
417    print ZEPHYR "Playback completed with the following errors:\n";
418    print ZEPHYR $_;
419    while (<OGGSTATUS>) {
420      print ZEPHYR $_;
421    }
422  } else {
423    print ZEPHYR "Playback completed successfully.\n";
424  }
425  close(OGGSTATUS);
426  unlink(OGGSTATUS);
427
428  close(ZEPHYR);
429}
430
431
432# Play an OggVorbis audio file
433sub play_ogg_audio {
434  # Retrieve those command line opts.
435  my %opts = %{shift(@_)};
436
437  # Get ogginfo stuff
438  open(OGGINFO, "/mit/sipb/bin/ogginfo $opts{'d'}/$opts{'e'}|");
439  while (<OGGINFO>) {
440    if (/(.*)=(.*)/) {
441      $ogginfo{lc("$1")} = $2;
442    }
443  }
444  close(OGGINFO);
445
446  # If there's no title, print the filename
447  if (!$ogginfo{'title'}) {
448    print ZEPHYR "No ogginfo data found\n";
449    print ZEPHYR "Filename: $opts{'J'}\n";
450  } else {
451    print ZEPHYR "Title          : $ogginfo{'title'}\n";
452    print ZEPHYR "Artist         : $ogginfo{'artist'}\n";
453    print ZEPHYR "Album          : $ogginfo{'album'}\n";
454    print ZEPHYR "Track #        : $ogginfo{'tracknumber'}\n";
455
456    # others
457    %lessinfo = %ogginfo;
458    delete $lessinfo{'filename'};
459    delete $lessinfo{'title'};
460    delete $lessinfo{'artist'};
461    delete $lessinfo{'album'};
462    delete $lessinfo{'tracknumber'};
463    delete $lessinfo{'header_integrity'};
464    delete $lessinfo{'stream_integrity'};
465    delete $lessinfo{'file_truncated'};
466    delete $lessinfo{'version'};
467    delete $lessinfo{'channels'};
468    delete $lessinfo{'bitrate_upper'};
469    delete $lessinfo{'bitrate_nominal'};
470    delete $lessinfo{'bitrate_lower'};
471    delete $lessinfo{'bitrate_average'};
472    delete $lessinfo{'length'};
473    delete $lessinfo{'playtime'};
474    delete $lessinfo{'kbps'};
475    delete $lessinfo{'time'};
476    delete $lessinfo{'rg_radio'};
477    delete $lessinfo{'rg_audiophile'};
478    delete $lessinfo{'rg_peak'};
479    delete $lessinfo{'replaygain_album_peak'};
480    delete $lessinfo{'replaygain_track_peak'};
481    delete $lessinfo{'replaygain_album_gain'};
482    delete $lessinfo{'replaygain_track_gain'};
483
484    while (($key,$val) = each %lessinfo) {
485      printf ZEPHYR "%-15s: %s\n", $key, $val;
486    }
487  }
488
489  printf ZEPHYR "\nOgg Vorbis, average %.1f kbit/s, %d channels\n\n",
490    $ogginfo{'bitrate_average'}/1024, $ogginfo{'channels'};
491  print ZEPHYR "Track length: $ogginfo{'playtime'}s\n";
492  close(ZEPHYR);
493
494  # Play the file
495
496  system("chmod a+rw /dev/audio");
497  system("ps -aef | grep ogg123 | awk '{print $2}' | xargs kill -9");
498  system("ps -aef | grep mpg123 | awk '{print $2}' | xargs kill -9");
499  system("/mit/sipb/bin/ogg123 -b 40000 -dau -q -f - - 2> /tmp/ogg123.out | audioplay");
500
501  # Done. Status:
502  open(ZEPHYR, '|/usr/athena/bin/zwrite -d -n -c sipb-auto -i sipbmp3@xcb -s "SIPB LPR music spooler"');
503
504  # Check if there were any errors
505  open(OGGSTATUS, "/tmp/ogg123.out");
506  if ($_ = <OGGSTATUS>) {
507    print ZEPHYR "Playback completed with the following errors:\n";
508    print ZEPHYR $_;
509    while (<OGGSTATUS>) {
510      print ZEPHYR $_;
511    }
512  } else {
513    print ZEPHYR "Playback completed successfully.\n";
514    # Repeat tag data for those playing at home
515    if (!$ogginfo{'title'}) {
516      print ZEPHYR "No ogginfo data found\n";
517      print ZEPHYR "Filename: $opts{'J'}\n\n";
518    } else {
519      print ZEPHYR "Title          : $ogginfo{'title'}\n";
520      print ZEPHYR "Artist         : $ogginfo{'artist'}\n";
521      print ZEPHYR "Album          : $ogginfo{'album'}\n";
522      print ZEPHYR "Track #        : $ogginfo{'tracknumber'}\n";
523
524      # others
525      while (($key,$val) = each %lessinfo) {
526        printf ZEPHYR "%-15s: %s\n", $key, $val;
527      }
528    }
529  }
530
531  close(OGGSTATUS);
532  unlink(OGGSTATUS);
533
534  close(ZEPHYR);
535}
Note: See TracBrowser for help on using the repository browser.