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

debianmacno-cupsnodebathenaweb
Last change on this file since f1ba976 was f1ba976, checked in by Jessica B. Hamrick <jhamrick@…>, 14 years ago

[I don't know who actually made this change]
Fixed the youtube-dl command.

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