source: gutenbach/debian/lib/sipbmp3-filter @ 82d34e6

debianmacno-cupsnodebathenaweb
Last change on this file since 82d34e6 was 82d34e6, checked in by jhawk <jhawk>, 22 years ago

Put under RCS.
Don't demand EXT-format, play straight URLs too based on content-type.

  • 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.6 2003-08-11 02:07:06 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 "audio/ogg") { $format="OGG" }
156          else {
157              print ZEPHYR "Unknown Content-Type $contenttype trying to /mit/sipb/bin/w3m -dump_head $uri\n";
158              close(ZEPHYR);
159          }
160      } else {
161        print ZEPHYR "Couldn't read URI for external reference\n";
162        close(ZEPHYR);
163      }
164  } else {
165      print ZEPHYR "Unknown syntax in play_external_reference(): $magic\n";
166      close(ZEPHYR);
167  }
168
169    # Echo the rest to the zephyr
170    while (<STDIN>) {
171      print ZEPHYR $_;
172    }
173    print ZEPHYR "\n";
174
175    # Play the thing the right way
176    if (($format eq "MP3") ||
177        ($format eq "mp3")) {
178      print ZEPHYR "Playing MP3 audio stream...\n";
179      close(ZEPHYR);
180      &play_mpeg_stream($uri, $userpass);
181    } elsif (($format eq "OGG") ||
182             ($format eq "ogg")) {
183      print ZEPHYR "Playing OggVorbis audio stream...\n";
184      close(ZEPHYR);
185      &play_ogg_stream($uri, $userpass);
186    } else {
187      print ZEPHYR "Unrecognized stream format: $format\n";
188      close(ZEPHYR);
189    }
190}
191
192
193# Play an MPEG audio stream
194# play_mpeg_stream(URI, userpass)
195sub play_mpeg_stream {
196  my $uri = shift(@_);
197  my $userpass = shift(@_);
198
199  # Add the user:pass argument if is was given to us
200  my $up = '';
201  if ($userpass) {
202    $up = '-u ' . $userpass;
203  }
204
205  system("ps ax | grep ogg123 | awk '{print $2}' | xargs kill -9");
206  system("ps ax | grep mpg123 | awk '{print $2}' | xargs kill -9");
207  system("chmod a+rw /dev/audio");
208  system("/mit/infoagents/bin/mpg123 -b 16384 -q $up $uri >/tmp/mpg123.out 2>&1");
209
210  # Done. Status:
211  open(ZEPHYR, '|/usr/athena/bin/zwrite -d -n -c sipb-auto -i sipbmp3@xcb -s "SIPB LPR music spooler"');
212
213  # Check if there were any errors
214  open(MP3STATUS, "/tmp/mpg123.out");
215  if ($_ = <MP3STATUS>) {
216    print ZEPHYR "Playback completed with the following errors:\n";
217    print ZEPHYR $_;
218    while (<MP3STATUS>) {
219      print ZEPHYR $_;
220    }
221  } else {
222    print ZEPHYR "Playback completed successfully.\n";
223  }
224  close(MP3STATUS);
225  unlink(MP3STATUS);
226
227  close(ZEPHYR);
228}
229
230# ID3 comments often have useless crap because tools like iTunes were
231# written by drooling idiots
232sub filter_comment {
233  my $comment = shift(@_);
234
235  if ($comment =~ /^engiTunes_CDDB/) {
236    return undef;
237  }
238  return $comment;
239}
240
241
242# Play an MPEG audio file
243sub play_mpeg_audio {
244    # Retrieve those command line opts.
245    my %opts = %{shift(@_)};
246
247    my %MPEGModes = ( 0 => "stereo",
248                      1 => "joint-stereo",
249                      2 => "dual-channel",
250                      3 => "single-channel");
251
252    # If it's an MP3 file, try to extract useful data
253    my $tag = get_mp3tag("$opts{'d'}/$opts{'e'}");
254    if (!$tag) {
255        print ZEPHYR "No ID3 tag found\n";
256        my @fnamearray = split /,/, $opts{'J'};
257        foreach $fname (@fnamearray) {
258            print ZEPHYR "Filename: $fname\n";
259        }
260#           print ZEPHYR "Filename: $opts{'J'}\n\n";
261    } else {
262      print ZEPHYR "Title          : $tag->{TITLE}\n";
263      print ZEPHYR "Artist         : $tag->{ARTIST}\n";
264      print ZEPHYR "Album          : $tag->{ALBUM}\n";
265      if ($tag->{TRACKNUM} =~ /(.*)\/.*/) {
266          $tag->{TRACKNUM} = $1;
267      }
268      if ($tag->{TRACKNUM}) {
269          print ZEPHYR "Track #        : $tag->{TRACKNUM}\n";
270      }
271      if ($tag->{YEAR}) {
272        print ZEPHYR "Year           : $tag->{YEAR}\n";
273      }
274      if ($tag->{GENRE}) {
275        # iTunes (?) does something weird with genres, leaving them
276        # as the string "(##)" where ## is the genre type. Let's deal
277        # with this.
278        if ($tag->{GENRE} =~ /^\((\d*)\)$/) {
279          $tag->{GENRE} = $MP3::Info::mp3_genres[$1];
280        }
281        if ($tag->{GENRE} =~ /^(\d*)$/) {
282          $tag->{GENRE} = $MP3::Info::mp3_genres[$1];
283        }
284        print ZEPHYR "Genre          : $tag->{GENRE}\n";
285      }
286      if (ref $tag->{COMMENT} eq 'ARRAY') {
287        foreach $index (0 .. $#{$tag->{COMMENT}}) {
288          if ($comment = filter_comment(@{$tag->{COMMENT}}[$index])) {
289            print ZEPHYR "Comment        : $comment\n";
290          }
291        }
292      } elsif ($tag->{COMMENT}) {
293        if ($comment = filter_comment($tag->{COMMENT})) {
294          print ZEPHYR "Comment        : $comment\n";
295        }
296      }
297
298      # Maybe get some extended ID3v2 info?
299      my $v2tag = get_mp3tag("$opts{'d'}/$opts{'e'}", 2, 1);
300      %lessinfo = %$v2tag;
301      foreach $dtag (keys %MP3::Info::v2_to_v1_names) {
302        delete $lessinfo{$dtag};
303      }
304      delete $lessinfo{'GENRE'};
305      # Delete annoying useless crap
306      my @bad_tags = ('GEO', 'GEOB', # General encapsulated object
307                      'PIC', 'APIC', # Attached picture.
308                      );
309      foreach $dtag (@bad_tags) {
310          delete $lessinfo{$dtag};
311      }
312      while (($key,$val) = each %lessinfo) {
313        printf ZEPHYR "%-15s: %s\n", $MP3::Info::v2_tag_names{$key}, $val;
314      }
315      print ZEPHYR "\n";
316    }
317
318    my $info = get_mp3info("$opts{'d'}/$opts{'e'}");
319    if (!$info) {
320        print ZEPHYR "No MPEG header found\n";
321    } else {
322        print ZEPHYR "MPEG $info->{VERSION} layer $info->{LAYER}, ";
323        if ($info->{VBR}) {
324            print ZEPHYR "VBR ";
325        }
326        print ZEPHYR "$info->{BITRATE} kbit/s, $info->{FREQUENCY} kHz ";
327        print ZEPHYR $MPEGModes{$info->{STEREO}};
328        print ZEPHYR "\n\n";
329        printf ZEPHYR "Track length: %d:%02ds\n", $info->{MM}, $info->{SS};
330    }
331    close(ZEPHYR);
332
333    # Play the file
334    # mpg123 is a crock.  If you don't give it -q, it needs to be on a pty
335    # or it SEGVs. Really.
336
337    system("chmod a+rw /dev/audio");
338    system("ps ax | grep ogg123 | awk '{print $2}' | xargs kill -9");
339    system("ps ax | grep mpg123 | awk '{print $2}' | xargs kill -9");
340    system("/mit/infoagents/bin/mpg123 -b 16384 -q - >/tmp/mpg123.out 2>&1");
341
342    # Done. Status:
343    open(ZEPHYR, '|/usr/athena/bin/zwrite -d -n -c sipb-auto -i sipbmp3@xcb -s "SIPB LPR music spooler"');
344
345    # Check if there were any errors
346    open(MP3STATUS, "/tmp/mpg123.out");
347    if ($_ = <MP3STATUS>) {
348        print ZEPHYR "Playback completed with the following errors:\n";
349        print ZEPHYR $_;
350        while (<MP3STATUS>) {
351            print ZEPHYR $_;
352        }
353    } else {
354        print ZEPHYR "Playback completed successfully.\n";
355        # Repeat tag data for those playing at home
356        if (!$tag) {
357          print ZEPHYR "No ID3 tag found\n";
358          print ZEPHYR "Filename: $opts{'J'}\n\n";
359        } else {
360          print ZEPHYR "Title          : $tag->{TITLE}\n";
361          print ZEPHYR "Artist         : $tag->{ARTIST}\n";
362          print ZEPHYR "Album          : $tag->{ALBUM}\n";
363          if ($tag->{TRACKNUM} =~ /(.*)\/.*/) {
364              $tag->{TRACKNUM} = $1;
365          }
366          if ($tag->{TRACKNUM}) {
367              print ZEPHYR "Track #        : $tag->{TRACKNUM}\n";
368          }
369          if ($tag->{YEAR}) {
370            print ZEPHYR "Year           : $tag->{YEAR}\n";
371          }
372          if ($tag->{GENRE}) {
373              print ZEPHYR "Genre          : $tag->{GENRE}\n";
374          }
375          if (ref $tag->{COMMENT} eq 'ARRAY') {
376            foreach $index (0 .. $#{$tag->{COMMENT}}) {
377              if ($comment = filter_comment(@{$tag->{COMMENT}}[$index])) {
378                print ZEPHYR "Comment        : $comment\n";
379              }
380            }
381          } elsif ($tag->{COMMENT}) {
382            if ($comment = filter_comment($tag->{COMMENT})) {
383              print ZEPHYR "Comment        : $comment\n";
384            }
385          }
386
387          # others
388          while (($key,$val) = each %lessinfo) {
389            printf ZEPHYR "%-15s: %s\n", $MP3::Info::v2_tag_names{$key}, $val;
390          }
391        }
392    }
393    close(MP3STATUS);
394    unlink(MP3STATUS);
395
396    close(ZEPHYR);
397}
398
399# Play an OggVorbis audio stream (doesn't support auth!)
400# play_ogg_stream(URI, userpass)
401sub play_ogg_stream {
402  my $uri = shift(@_);
403  my $userpass = shift(@_);
404
405  system("chmod a+rw /dev/audio");
406  system("ps -aef | grep ogg123 | awk '{print $2}' | xargs kill -9");
407  system("ps -aef | grep mpg123 | awk '{print $2}' | xargs kill -9");
408  system("/mit/sipb/bin/ogg123 -b 40000 -dau -q -f - $uri 2> /tmp/ogg123.out | audioplay");
409
410  # Done. Status:
411  open(ZEPHYR, '|/usr/athena/bin/zwrite -d -n -c sipb-auto -i sipbmp3@xcb -s "SIPB LPR music spooler"');
412
413  # Check if there were any errors
414  open(OGGSTATUS, "/tmp/ogg123.out");
415  if ($_ = <OGGSTATUS>) {
416    print ZEPHYR "Playback completed with the following errors:\n";
417    print ZEPHYR $_;
418    while (<OGGSTATUS>) {
419      print ZEPHYR $_;
420    }
421  } else {
422    print ZEPHYR "Playback completed successfully.\n";
423  }
424  close(OGGSTATUS);
425  unlink(OGGSTATUS);
426
427  close(ZEPHYR);
428}
429
430
431# Play an OggVorbis audio file
432sub play_ogg_audio {
433  # Retrieve those command line opts.
434  my %opts = %{shift(@_)};
435
436  # Get ogginfo stuff
437  open(OGGINFO, "/mit/sipb/bin/ogginfo $opts{'d'}/$opts{'e'}|");
438  while (<OGGINFO>) {
439    if (/(.*)=(.*)/) {
440      $ogginfo{lc("$1")} = $2;
441    }
442  }
443  close(OGGINFO);
444
445  # If there's no title, print the filename
446  if (!$ogginfo{'title'}) {
447    print ZEPHYR "No ogginfo data found\n";
448    print ZEPHYR "Filename: $opts{'J'}\n";
449  } else {
450    print ZEPHYR "Title          : $ogginfo{'title'}\n";
451    print ZEPHYR "Artist         : $ogginfo{'artist'}\n";
452    print ZEPHYR "Album          : $ogginfo{'album'}\n";
453    print ZEPHYR "Track #        : $ogginfo{'tracknumber'}\n";
454
455    # others
456    %lessinfo = %ogginfo;
457    delete $lessinfo{'filename'};
458    delete $lessinfo{'title'};
459    delete $lessinfo{'artist'};
460    delete $lessinfo{'album'};
461    delete $lessinfo{'tracknumber'};
462    delete $lessinfo{'header_integrity'};
463    delete $lessinfo{'stream_integrity'};
464    delete $lessinfo{'file_truncated'};
465    delete $lessinfo{'version'};
466    delete $lessinfo{'channels'};
467    delete $lessinfo{'bitrate_upper'};
468    delete $lessinfo{'bitrate_nominal'};
469    delete $lessinfo{'bitrate_lower'};
470    delete $lessinfo{'bitrate_average'};
471    delete $lessinfo{'length'};
472    delete $lessinfo{'playtime'};
473    delete $lessinfo{'kbps'};
474    delete $lessinfo{'time'};
475    delete $lessinfo{'rg_radio'};
476    delete $lessinfo{'rg_audiophile'};
477    delete $lessinfo{'rg_peak'};
478    delete $lessinfo{'replaygain_album_peak'};
479    delete $lessinfo{'replaygain_track_peak'};
480    delete $lessinfo{'replaygain_album_gain'};
481    delete $lessinfo{'replaygain_track_gain'};
482
483    while (($key,$val) = each %lessinfo) {
484      printf ZEPHYR "%-15s: %s\n", $key, $val;
485    }
486  }
487
488  printf ZEPHYR "\nOgg Vorbis, average %.1f kbit/s, %d channels\n\n",
489    $ogginfo{'bitrate_average'}/1024, $ogginfo{'channels'};
490  print ZEPHYR "Track length: $ogginfo{'playtime'}s\n";
491  close(ZEPHYR);
492
493  # Play the file
494
495  system("chmod a+rw /dev/audio");
496  system("ps -aef | grep ogg123 | awk '{print $2}' | xargs kill -9");
497  system("ps -aef | grep mpg123 | awk '{print $2}' | xargs kill -9");
498  system("/mit/sipb/bin/ogg123 -b 40000 -dau -q -f - - 2> /tmp/ogg123.out | audioplay");
499
500  # Done. Status:
501  open(ZEPHYR, '|/usr/athena/bin/zwrite -d -n -c sipb-auto -i sipbmp3@xcb -s "SIPB LPR music spooler"');
502
503  # Check if there were any errors
504  open(OGGSTATUS, "/tmp/ogg123.out");
505  if ($_ = <OGGSTATUS>) {
506    print ZEPHYR "Playback completed with the following errors:\n";
507    print ZEPHYR $_;
508    while (<OGGSTATUS>) {
509      print ZEPHYR $_;
510    }
511  } else {
512    print ZEPHYR "Playback completed successfully.\n";
513    # Repeat tag data for those playing at home
514    if (!$ogginfo{'title'}) {
515      print ZEPHYR "No ogginfo data found\n";
516      print ZEPHYR "Filename: $opts{'J'}\n\n";
517    } else {
518      print ZEPHYR "Title          : $ogginfo{'title'}\n";
519      print ZEPHYR "Artist         : $ogginfo{'artist'}\n";
520      print ZEPHYR "Album          : $ogginfo{'album'}\n";
521      print ZEPHYR "Track #        : $ogginfo{'tracknumber'}\n";
522
523      # others
524      while (($key,$val) = each %lessinfo) {
525        printf ZEPHYR "%-15s: %s\n", $key, $val;
526      }
527    }
528  }
529
530  close(OGGSTATUS);
531  unlink(OGGSTATUS);
532
533  close(ZEPHYR);
534}
Note: See TracBrowser for help on using the repository browser.