Wheel/Audio/Mad.pm untested

filter: Statementstmt 0.0% 0 / 298 Branchbran 0.0% 0 / 112 Conditioncond 0.0% 0 / 83 MC/DCmcdc 0.0% 0 / 42 Subroutinesub 0.0% 0 / 28 Podpod 0.0% 0 / 19 totaltotal 0.0% 0 / 582 CC 57 SCAR 36.5
CC
57
Cov
0%
__d_decoder_cycle
110.0
decoder_set
90.0
__d_decoder_reset
56.0
CRAP 38.5
1 package POE::Wheel::Audio::Mad;
2 require 5.6.0;
3  
4 use strict;
5 use warnings;
6  
7 our $VERSION = '0.3';
8  
9 ## version 0.3 basically means, I've rewritten this a few times,
10 ## screwed version numbers completely up, came up with this idea,
11 ## modified it twice, and just barely documented it. That means
12 ## there's pod to describe it's usage, but very little in the
13 ## way of interal comments -- wait for 0.4; the comment overhaul
14 ## release.
15  
16 use Carp qw(croak);
17  
18 use POE;
19 use POE::Wheel;
20  
21 use Audio::Mad qw(:all);
22 use Audio::Mad::Util qw(mad_stream_info mad_parse_xing mad_cbr_seek mad_xing_seek);
23  
24 use Audio::OSS qw(:funcs :formats :mixer);
25  
26 ## the list of states that we will define in our parent session.
27 our @STATES = qw(
28 decoder_shutdown decoder_close decoder_set decoder_info
29 decoder_open decoder_play decoder_pause decoder_stop decoder_seek
30  
31 __d_input_open __d_input_read __d_input_close
32 __d_output_open __d_output_close
33 __d_decoder_reset __d_decoder_cycle
34 );
35  
36 ##############################################################################
37  
38 sub new {
39 my ($class, %args) = @_;
40  
41 croak "$class requires a working POE Kernel" unless (defined($poe_kernel));
42 croak "$class requires a message_event paramater" unless (defined($args{message_event}));
43  
44 my $self = bless({
45 message_event => $args{message_event},
46 wheel_id => POE::Wheel::allocate_wheel_id(),
47 }, $class);
48  
49 $self->{options} = {
50 output_close_on_pause => $args{output_close_on_pause} || 0,
51 output_close_on_stop => $args{output_close_on_stop} || 1,
52
53 decoder_progress_range => $args{decoder_progress_range} || 100,
54 decoder_play_on_open => $args{decoder_play_on_open} || 0,
55 };
56  
57 $self->{input} = {
58 state => 'CLOSED',
59
60 handle => undef,
61 filename => '',
62 stats => [(0)x13],
63
64 buffer => '',
65 info => {},
66 };
67
68 $self->{decoder} = {
69 state => 'CLOSED',
70
71 stream => undef,
72 frame => undef,
73 synth => undef,
74 resample => undef,
75 dither => undef,
76  
77 played => undef,
78 printed => 0,
79 progress => 0,
80 frames => 0,
81 };
82
83 $self->{output} = {
84 state => 'CLOSED',
85
86 handle => undef,
87  
88 device => $args{output_device} || '/dev/dsp',
89 samplerate => $args{output_samplerate} || 44100,
90 format => $args{output_format} || AFMT_S16_LE,
91
92 mixer_device => $args{mixer_device} || '/dev/mixer',
93 mixer_balance => $args{mixer_balance} || 50,
94 mixer_volume => $args{mixer_volume} || 50,
95 mixer_pcm => $args{mixer_pcm} || 60
96 };
97
98 for (@STATES) {
99 croak "$class failed to define state: $_\n" if ($poe_kernel->state( $_ => $self ));
100 }
101
102 return $self;
103 }
104  
105 sub DESTROY {
106 my ($self) = @_;
107
108 for (@STATES) { $poe_kernel->state( $_ ) }
109 POE::Wheel::free_wheel_id( $self->{wheel_id} );
110 }
111  
112 sub decoder_shutdown {
113 my ($kernel, $self, $session) = @_[KERNEL, OBJECT, SESSION];
114  
115 ## we ->call() the next few functions to make sure that
116 ## they finish before we disappear as a session..
117
118 $kernel->call($session, '__d_output_close');
119 $kernel->call($session, '__d_input_close');
120 $kernel->call($session, '__d_decoder_reset');
121  
122 ## let everyone know that we're dying..
123 $kernel->yield($self->{message_event}, {
124 id => 'DECODER_SHUTDOWN_SUCCESS',
125 data => ''
126 });
127
128 $kernel->yield('shutdown');
129 }
130  
131 ##############################################################################
132  
133 sub decoder_open {
134 my ($self, $kernel, $session, $args) = @_[OBJECT, KERNEL, SESSION, ARG0];
135
136 my ($filename, $play) = @{$args}{qw(filename play)};
137  
138 ## call deeper to accomplish the actual opening
139 ## and scanning of the stream..
140 $kernel->call($session, '__d_input_open', $filename);
141  
142 ## we couldn't find or open the file, or we scanned
143 ## it and didn't get any valid stream information..
144 return undef unless (
145 $self->{input}->{state} eq 'OPEN' &&
146 $self->{input}->{filename} eq $filename
147 );
148
149 ## reset the decoder..
150 $kernel->call($session, '__d_decoder_reset');
151
152 ## and start playing if that's what we're supposed to do..
153 $kernel->yield('decoder_play') if ($play || $self->{options}->{decoder_play_on_open});
154 }
155  
156 sub decoder_close {
157 my ($kernel, $session) = @_[KERNEL, SESSION];
158
159 ## close is rather heavy handed, it does everything a
160 ## shudown does without actually disappearing..
161  
162 $kernel->call($session, '__d_output_close');
163 $kernel->call($session, '__d_input_close');
164 $kernel->call($session, '__d_decoder_reset');
165 }
166  
167 sub decoder_play {
168 my ($self, $kernel, $session) = @_[OBJECT, KERNEL, SESSION];
169
170 ## check to see if we have a file to play, and generate
171 ## an event if we don't..
172
173 unless ($self->{input}->{state} eq 'OPEN') {
174 $kernel->yield($self->{message_event}, {
175 id => 'DECODER_PLAY_FAILED',
176 data => 'no input file open'
177 });
178 return undef;
179 }
180
181 ## make sure that the output is open, or at least try really hard to open it..
182
183 $kernel->call($session, '__d_output_open') unless ($self->{output}->{state} eq 'OPEN');
184 return undef unless ($self->{output}->{state} eq 'OPEN');
185  
186 ## update our state to indicate that we are playing, and generate
187 ## an event to tell everyone we are playing..
188  
189 $self->{decoder}->{state} = 'PLAYING';
190 $kernel->yield($self->{message_event}, {
191 id => 'DECODER_STATUS_DATA',
192 data => { state => 'PLAYING' }
193 });
194
195 ## let decoder_cycle spin off on it's chore..
196
197 $kernel->yield('__d_decoder_cycle');
198 }
199  
200 sub decoder_pause {
201 my ($self, $kernel) = @_[OBJECT, KERNEL];
202
203 ## check to see that we are currently playing a file
204 ## and generate an event if we aren't..
205 unless ($self->{decoder}->{state} eq 'PLAYING') {
206 $kernel->yield($self->{message_event}, {
207 id => 'DECODER_PAUSE_FAILED',
208 data => 'not playing file'
209 });
210 return undef;
211 }
212
213 ## close down the output device if we're told to do so..
214
215 $kernel->yield('__d_output_close') if ($self->{options}->{output_close_on_pause});
216  
217 ## indicate we are paused, and tell everyone about it..
218  
219 $self->{decoder}->{state} = 'PAUSED';
220 $kernel->yield($self->{message_event}, {
221 id => 'DECODER_STATUS_DATA',
222 data => { state => 'PAUSED' }
223 });
224 }
225  
226 sub decoder_stop {
227 my ($self, $kernel, $session) = @_[OBJECT, KERNEL, SESSION];
228  
229 ## make sure we can stop and generate something if not..
230
231 unless (
232 $self->{decoder}->{state} eq 'PLAYING' ||
233 $self->{decoder}->{state} eq 'PAUSED'
234 ) {
235 $kernel->yield($self->{message_event}, {
236 id => 'DECODER_STOP_FAILED',
237 data => 'not playing file'
238 });
239 return undef;
240 }
241  
242 ## save and indicate our current status..
243  
244 $self->{decoder}->{state} = 'STOPPED';
245 $kernel->yield($self->{message_event}, {
246 id => 'DECODER_STATUS_DATA',
247 data => { state => 'STOPPED' }
248 });
249  
250 ## here we seek the input file back to the beginning, and close
251 ## the output device if that's what we're supposed to do.
252  
253 $kernel->yield('decoder_seek', { position => 0, range => 1 });
254 $kernel->yield('__d_output_close') if ($self->{options}->{output_close_on_stop});
255 }
256  
257 sub decoder_seek {
258 my ($kernel, $self, $session, $args) = @_[KERNEL, OBJECT, SESSION, ARG0];
259 my ($position, $range) = @{$args}{qw(position range)};
260 my ($input, $decoder) = @{$self}{qw(input decoder)};
261  
262 ## check that we have an open file, and generate something if not..
263  
264 unless ($input->{state} eq 'OPEN') {
265 $kernel->yield($self->{message_event}, {
266 id => 'INPUT_SEEK_FAILED',
267 data => 'no input file open'
268 });
269 return undef;
270 }
271  
272 ## seeking is kind of tricky.. so we use some support
273 ## functions that tell us how to seek. pos is the
274 ## file position to seek to, and frame is the frame
275 ## that will be played next..
276
277 my ($pos, $frame);
278 if ($input->{info}->{s_vbr} == 0) {
279 ## cbr seeking is easy, see the referenced
280 ## function (below)..
281 ($pos, $frame) = mad_cbr_seek(
282 position => $position,
283 range => $range,
284 frames => $input->{info}->{s_frames},
285 size => $input->{info}->{f_size}
286 );
287 } else {
288 ## vbr seeking isn't soo easy, and requires us to use
289 ## an automatically generated toc from the mad_stream_info
290 ## routine..
291 ($pos, $frame) = mad_xing_seek(
292 position => $position,
293 range => $range,
294 frames => $input->{info}->{s_frames},
295 toc => $input->{info}->{xing_toc}
296 );
297 }
298
299 ## if it's not a valid place to seek, just forget it..
300
301 return undef unless (defined($pos) && $pos > -1);
302  
303 ## if we're seeking somewhere other than the beginning, take
304 ## a copy of the frame duration, and multiply it by our
305 ## destination frame -- this keeps DECODER_FRAME_DATA accurate.
306
307 if (defined($frame) && $frame > 0) {
308 $decoder->{played} = $input->{info}->{s_frame_duration}->new_copy();
309 $decoder->{played}->multiply($frame);
310 } else {
311
312 ## otherwise, it's the beginning and we can just use a
313 ## zeroed out timer..
314
315 $decoder->{played} = new Audio::Mad::Timer;
316 }
317
318 ## force our 'printed' and 'progress' values out of date
319 ## so that they are updated and events get generated as
320 ## soon as we return to playing..
321
322 $decoder->{printed} = -1;
323 $decoder->{progress} = -1;
324
325 ## actually perform the seek..
326
327 CORE::seek($input->{handle}, $pos, 0);
328
329 ## clear our stream buffer, avoids having to drain the
330 ## buffer before we seek, and helps prevent the audio
331 ## from skipping and popping..
332
333 $input->{buffer} = '';
334  
335 ## tell the decoder to bleed off three frames before
336 ## synthesizing audio data from the stream.. helps
337 ## prevent audio skips and pops..
338  
339 $decoder->{seeking} = 3;
340
341 ## reset the stream buffer completely..
342
343 $decoder->{stream} = new Audio::Mad::Stream(MAD_OPTION_IGNORECRC);
344  
345 ## generate an event to let everyone know that the
346 ## stream position was just moved..
347
348 $kernel->yield($self->{message_event}, {
349 id => 'INPUT_SEEK_SUCCESS',
350 data => $pos
351 });
352
353 ## and jump into decoder_cycle unless we would already
354 ## do that soon..
355  
356 $kernel->yield('__d_decoder_cycle') unless ($decoder->{state} eq 'PLAYING');
357 }
358  
359 ## ugly, ugly, ugly.. but, it was quick. this is just an outpost for all
360 ## those abandoned options seen earlier, there are lots of problems with
361 ## the sub below, and they'll be fixed as soon as I come up with a good
362 ## options system, that allows us to be notified when particular options
363 ## get changed on us..
364  
365 # set option <option> <value>
366 # set mixer <volume|pcm|balance> <value>
367 sub decoder_set {
368 my ($self, $kernel, $session, $args) = @_[OBJECT, KERNEL, SESSION, ARG0];
369
370 my ($type, $key, $value) = @{$args}{qw(type key value)};
371 $type = '' unless (defined($type));
372
373 if (lc($type) eq 'option') {
374 unless (defined($self->{options}->{$key})) {
375 $kernel->yield($self->{message_event}, {
376 id => 'IPC_COMMAND_FAILED',
377 data => "OPTION unknown key $key"
378 });
379 return undef;
380 }
381
382 ## FIXME: gag, need better option system..
383 if ($key eq 'decoder_progress_range') { $self->{decoder}->{progress} = -1 }
384  
385 $self->{options}->{$key} = $value;
386 $kernel->yield($self->{message_event}, {
387 id => 'DECODER_OPTION_DATA',
388 data => { lc($key) => $value }
389 });
390 }
391 elsif (lc($type) eq 'mixer') {
392 if ($key eq 'volume') { $self->{output}->{mixer_volume} = $value }
393 elsif ($key eq 'pcm') { $self->{output}->{mixer_pcm} = $value }
394 elsif ($key eq 'balance') { $self->{output}->{mixer_balance} = $value }
395 else {
396 $kernel->yield($self->{message_event}, {
397 id => 'IPC_COMMAND_FAILED',
398 data => "MIXER unknown key $key"
399 });
400 }
401  
402 _mixer_update($self->{output});
403 $kernel->yield($self->{message_event}, {
404 id => 'DSP_MIXER_DATA',
405 data => {
406 balance => $self->{output}->{mixer_balance},
407 volume => $self->{output}->{mixer_volume},
408 pcm => $self->{output}->{mixer_pcm}
409 }
410 });
411 } else {
412 $kernel->yield($self->{message_event}, {
413 id => 'IPC_COMMAND_FAILED',
414 data => "SET unknown type $type"
415 });
416 }
417 }
418  
419 sub decoder_info {
420 my ($self, $kernel, $args) = @_[OBJECT, KERNEL, ARG0];
421 my $type = $args->{type};
422  
423 ## this is a simple routine, designed to coherce the decoding
424 ## engine into immediately giving up some information about one
425 ## of it's subsystems.. pretty simple stuff here.
426  
427 if (lc($type) eq 'decoder') {
428 $kernel->yield($self->{message_event}, {
429 id => 'DECODER_OPTION_DATA',
430 data => $self->{options}
431 });
432
433 $kernel->yield($self->{message_event}, {
434 id => 'DECODER_STATUS_DATA',
435 data => { state => $self->{decoder}->{state} }
436 });
437
438 $kernel->yield($self->{message_event}, {
439 id => 'DECODER_FRAME_DATA',
440 data => {
441 played => $self->{decoder}->{printed},
442 progress => $self->{decoder}->{progress}
443 }
444 });
445 } elsif (lc($type) eq 'input') {
446 $kernel->yield($self->{message_event}, {
447 id => 'INPUT_STATUS_DATA',
448 data => { state => $self->{input}->{state} }
449 });
450
451 $kernel->yield($self->{message_event}, {
452 id => 'INPUT_INFO_DATA',
453 data => $self->{input}->{info}
454 }) if ($self->{input}->{state} eq 'OPEN');
455 } elsif (lc($type) eq 'dsp') {
456 $kernel->yield($self->{message_event}, {
457 id => 'DSP_MIXER_DATA',
458 data => {
459 balance => $self->{output}->{mixer_balance},
460 volume => $self->{output}->{mixer_volume},
461 pcm => $self->{output}->{mixer_pcm}
462 }
463 });
464
465 $kernel->yield($self->{message_event}, {
466 id => 'DSP_STATUS_DATA',
467 data => { state => $self->{output}->{state} }
468 });
469 } else {
470 $kernel->yield($self->{message_event}, {
471 id => 'IPC_COMMAND_FAILED',
472 data => "INFO unknown type $type"
473 });
474 }
475 }
476  
477 ##############################################################################
478  
479 ## okay, here's the gritty subsystem kind of stuff. this is where all the
480 ## work actually happens -- and most of the logic is. stay close, it's
481 ## dark down here...
482  
483 sub __d_input_open {
484 my ($kernel, $self, $session, $filename) = @_[KERNEL, OBJECT, SESSION, ARG0];
485  
486 ## alias a hashref because we are lazy..
487  
488 my $input = $self->{input};
489
490 ## attempt to acquire a filehandle for our specified
491 ## file, if not, generate an event and quit..
492  
493 my ($handle);
494 CORE::open($handle, '<'.$filename) || do {
495 $kernel->yield($self->{message_event}, {
496 id => 'INPUT_OPEN_FAILED',
497 data => "$filename: $!",
498 });
499 return undef;
500 };
501
502 ## no we try to get some information on the stream, and
503 ## tell mad_stream_info to generate a toc so we can seek.
504 ## if we fail, tell everyone about it, and close the
505 ## stream..
506
507 my $info;
508 unless (defined($info = mad_stream_info($handle, 1))) {
509 $kernel->yield($self->{message_event}, {
510 id => 'INPUT_OPEN_FAILED',
511 data => "$filename: unable to find mpeg stream"
512 });
513 CORE::close($handle);
514 return undef;
515 };
516
517 ## we close down the old input handle unless it already is..
518
519 $kernel->call($session, '__d_input_close') unless ($input->{state} eq 'CLOSED');
520
521 ## after mad_stream_info runs the file position needs to be
522 ## moved back to the beginning..
523
524 CORE::seek($handle, 0, 0);
525
526 ## now we can track all the extra little information about our
527 ## new stream..
528
529 $input->{handle} = $handle;
530  
531 $input->{filename} = $filename;
532 $input->{stats} = [stat($input->{handle})];
533 $input->{info} = $info;
534  
535 ## mark that the input system is open, and send events to
536 ## everyone so they know about it too..
537  
538 $input->{state} = 'OPEN';
539  
540 $kernel->yield($self->{message_event}, {
541 id => 'INPUT_STATUS_DATA',
542 data => {
543 state => 'OPEN',
544 filename => $filename
545 }
546 });
547  
548 ## we make a copy of our stream information, drop out
549 ## the table of contents (can be very large)..
550  
551 my %info = %{$input->{info}};
552 delete $info{xing_toc};
553
554 ## and send it out to interested customers..
555
556 $kernel->yield($self->{message_event}, {
557 id => 'INPUT_INFO_DATA',
558 data => \%info
559 });
560 }
561  
562 sub __d_input_read {
563 my ($kernel, $self, $session) = @_[KERNEL, OBJECT, SESSION];
564  
565 ## alias a hashref (lazy) and requisition a temp variable..
566
567 my ($input, $temp) = ($self->{input}, '');
568  
569 ## keep track of everything from the end of the last fully
570 ## available frame to the end of the buffer..
571  
572 $temp = substr($input->{buffer}, $self->{decoder}->{stream}->next_frame())
573 if ($input->{buffer} ne '');
574  
575 ## attempt to read from our input handle..
576
577 if (sysread($input->{handle}, $input->{buffer}, 256000) == 0) {
578
579 ## the read returned 0, so we are at end of
580 ## file, generate an event to tell everyone,
581 ## and take appropriate action..
582
583 $kernel->yield($self->{message_event}, {
584 id => 'INPUT_EOF_WARNING',
585 data => $input->{filename}
586 });
587
588 $kernel->yield('__d_input_close');
589 $kernel->yield('__d_decoder_reset');
590 } else {
591
592 ## otherwise, we still have more stream to go.
593 ## reform the buffer with the end fragment from the
594 ## old buffer, and the newly read data..
595
596 $input->{buffer} = $temp . $input->{buffer};
597
598 ## tell the stream object about our new buffer..
599
600 $self->{decoder}->{stream}->buffer($input->{buffer});
601
602 ## and go back to work..
603
604 $kernel->yield('__d_decoder_cycle');
605 }
606 }
607  
608 sub __d_input_close {
609 my ($kernel, $self, $session) = @_[KERNEL, OBJECT, SESSION];
610  
611 ## shortcut a few variables..
612  
613 my $input = $self->{input};
614 my $filename = $input->{filename};
615  
616 ## leave unless there's something we could do..
617
618 return undef unless ($input->{state} eq 'OPEN');
619  
620 ## if we have a handle, try to close it, and warn users
621 ## if we can't..
622
623 if (defined($input->{handle})) {
624 CORE::close($input->{handle}) || $kernel->yield($self->{message_event}, {
625 id => 'INPUT_CLOSE_WARNING',
626 data => 'failed to close file handle'
627 });
628 }
629
630 ## reset our internal state data..
631
632 $input->{handle} = undef;
633 $input->{filename} = '';
634 $input->{stats} = [(0)x13];
635
636 $input->{buffer} = '';
637 $input->{info} = {};
638
639 $input->{state} = 'CLOSED';
640
641 ## and tell everyone about the new state..
642
643 $kernel->yield($self->{message_event}, {
644 id => 'INPUT_CLOSE_SUCCESS',
645 data => $filename
646 });
647
648 $kernel->yield($self->{message_event}, {
649 id => 'INPUT_STATUS_DATA',
650 data => { state => 'CLOSED' }
651 });
652 }
653  
654 sub __d_decoder_reset {
655 my ($self, $kernel, $session) = @_[OBJECT, KERNEL, SESSION];
656 my ($input, $output, $decoder) = @{$self}{qw(input output decoder)};
657  
658 ## first step: stop the decoder, and let everyone know
659 ## that's what just happened..
660  
661 $decoder->{state} = 'STOPPED';
662 $kernel->yield($self->{message_event}, {
663 id => 'DECODER_STATUS_DATA',
664 data => { state => 'STOPPED' }
665 });
666  
667 ## unless we have a file already open, there's not much
668 ## more to a reset..
669
670 return undef unless ($input->{state} eq 'OPEN');
671
672 ## otherwise, we have all kinds of neat stuff to setup..
673 ## fix: mad_dither_s16_le is an assumption, and a
674 ## non-portable one at that..
675
676 $decoder->{stream} = new Audio::Mad::Stream(MAD_OPTION_IGNORECRC);
677 $decoder->{frame} = new Audio::Mad::Frame;
678 $decoder->{synth} = new Audio::Mad::Synth;
679 $decoder->{dither} = new Audio::Mad::Dither(MAD_DITHER_S16_LE);
680  
681 $decoder->{played} = new Audio::Mad::Timer;
682 $decoder->{printed} = 0;
683 $decoder->{progress} = 0;
684 $decoder->{seeking} = 0;
685
686 ## update everyones idea of our progress on this stream..
687  
688 $kernel->yield($self->{message_event}, {
689 id => 'DECODER_FRAME_DATA',
690 data => { played => 0, progress => 0 }
691 });
692  
693 $decoder->{frames} = 0;
694
695 ## setup output if available..
696 if ($output->{state} eq 'OPEN') {
697
698 ## reset the dsp device..
699
700 dsp_reset($output->{handle});
701
702 ## turn stereo on or off depending on the
703 ## number of channels in our input stream..
704
705 if ($input->{info}->{s_mode} == 0) {
706 set_stereo($output->{handle}, 0);
707 } else {
708 set_stereo($output->{handle}, 1);
709 }
710
711 ## here we try to match the stream sampling rate to
712 ## the dsp sampling rate..
713
714 if ($output->{samplerate} == $input->{info}->{s_samplerate}) {
715  
716 ## resampling rates equal, we need to do nothing..
717 $decoder->{resample} = undef;
718  
719 } elsif (set_sps($output->{handle}, $input->{info}->{s_samplerate}) != $input->{info}->{s_samplerate}) {
720  
721 ## couldn't set the soundcard rate, so we need to
722 ## create ourselvs a Resample object..
723 $decoder->{resample} = new Audio::Mad::Resample($input->{info}->{s_samplerate}, $output->{samplerate});
724  
725 } else {
726  
727 ## succeded updating soundcard rate
728  
729 $output->{samplerate} =
730 $decoder->{samplerate} = $input->{info}->{s_samplerate};
731
732 $decoder->{resample} = undef;
733 }
734 } else {
735 ## the output device is not yet open, so the least we can
736 ## do is to see if our sampling rates our equal, and if not,
737 ## just create a resample object and use the default dsp
738 ## sampling rate..
739  
740 $decoder->{resample} = (
741 $input->{info}->{s_samplerate} != $output->{samplerate}
742 ? new Audio::Mad::Resample($input->{info}->{s_samplerate}, $output->{samplerate})
743 : undef
744 );
745 }
746 }
747  
748 ## here's where all the magic happens.. when I was first writing this
749 ## module I spent a lot of time trying to figure out an efficient
750 ## algorithm for calling this part of the state machine. My thinking
751 ## was that if I call this state once for each frame in a stream, and
752 ## this state makes a bunch of function calls (especially through XS
753 ## into Audio::Mad) that I would end up with HUGE overheads. I tried
754 ## everything I could to keep calls in here minimal, including
755 ## processing 3 or 5 frames per cycle, instead of one.
756  
757 ## truth is, I was wrong. premature optimization, I guess. Every
758 ## attempt I made at thinning calls to this state down, I still
759 ## ended up with huge amounts of CPU time being eaten. So I gave in
760 ## and went for the simplest solution: just try to do one frame
761 ## per cycle, and see what happens. Amazingly enough, my CPU
762 ## times settled right down, the playback was smooth, and I
763 ## was only seeing about a 2%-5% CPU time gain over mpg321.
764  
765 ## my thinking goes along these lines.. my computer can easily
766 ## decode more stream per second than my soundcard can play per
767 ## second.. so the solution was to let blocking slow me down..
768 ## We use a blocking write to the dsp below. If the DSP is
769 ## empty, we'll spin real fast here a few times and quickly
770 ## fill up the buffer -- at that point, we block for just a
771 ## few milliseconds every frame, enough to slow us down, but
772 ## not too much that it destroys interactivity. CPU times
773 ## stay in check, and we still have time left in the same
774 ## process to accomplish other tasks..
775  
776 ## I have written a curses based GUI on top of this module, and
777 ## it runs smoothly and without unexpected delays. Even holding
778 ## down a key to scroll the song list, I do not get skips or
779 ## pops in my playback -- but the CPU utilization gets as high
780 ## as 70%. So, the method may not be perfect, but it's enough
781 ## to make this a capable in-process mpeg decoder.
782  
783 sub __d_decoder_cycle {
784 my ($self, $kernel, $session) = @_[OBJECT, KERNEL, SESSION];
785
786 ## shortcut.. lazy.. stuff..
787 my $decoder = $self->{decoder};
788
789 ## start of our frame decoding bonanza..
790 FRAME: {
791
792 ## we only engage in this loop for two reasons, one: we wish
793 ## to play sound from the stream, or two: we wish to seek to
794 ## a specific point in the stream..
795 return undef unless ($decoder->{state} eq 'PLAYING' || $decoder->{seeking});
796
797 ## call mad_frame_decode(stream)..
798 if ($decoder->{frame}->decode($decoder->{stream}) == -1) {
799
800 ## immediately goto next frame if we got an
801 ## error that was recoverable..
802
803 redo FRAME if ($decoder->{stream}->err_ok());
804
805 ## shortcut the errorcode..
806
807 my $error = $decoder->{stream}->error();
808  
809 ## if we got an error because the buffer has
810 ## run try (BUFLEN) or the buffer hasn't been
811 ## set yet (BUFPTR)...
812  
813 if ($error == MAD_ERROR_BUFLEN || $error == MAD_ERROR_BUFPTR) {
814
815 ## then call the input subsystem to
816 ## read some data from our stream..
817
818 $kernel->yield('__d_input_read');
819
820 ## input_read will yield back to us to
821 ## resume playing if necessary..
822
823 return undef;
824 } else {
825
826 ## otherwise, we had a strange fatal error,
827 ## do our best to say something about it..
828
829 $kernel->yield($self->{message_event}, {
830 id => 'DECODER_FRAME_ERROR',
831 data => "unkown error: $error"
832 });
833
834 ## try to continue processing on the frame,
835 ## fix: eventually we should keep an error
836 ## counter and error out after x consecutive
837 ## errors..
838
839 redo FRAME;
840 }
841 }
842
843 ## keep track of some data, increment the frame
844 ## count, and our timer.
845
846 $decoder->{frames}++;
847 $decoder->{played}->add($decoder->{frame}->duration());
848  
849 ## data is defined in case we have any new DECODER_FRAME_DATA
850 ## we need to report, plus snatch the current time in miliseconds.
851  
852 my ($data, $ms) = ({}, $decoder->{played}->count(MAD_UNITS_MILLISECONDS));
853
854 ## if we haven't printed an update in the last half a second, or if
855 ## we haven't printed anything at all yet..
856
857 if ($ms - 500 > $decoder->{printed} || $decoder->{printed} == -1) {
858
859 ## then make a mark in our temporary data packet
860 ## about the current playtime in seconds. as well
861 ## as track the fact that we printed something
862 ## on this millisecond..
863
864 $data->{played} =
865 int(($decoder->{printed} = $ms) / 1000);
866 }
867
868 ## if we've played at least one second of the file -and-
869 ## the current progress number is greater than the old
870 ## one, or we haven't printed progress yet..
871
872 if (
873 $self->{input}->{info}->{s_seconds} &&
874 int(
875 (
876 $self->{options}->{decoder_progress_range} /
877 ($self->{input}->{info}->{s_seconds} * 1000)
878 )
879 * $ms
880 )
881 > $decoder->{progress} || $decoder->{progress} == -1
882 ) {
883
884 ## then set the progress in both the data packet
885 ## and our internal state..
886
887 ## to get the progress number (releative to the
888 ## decoder_progress_range option): divide the
889 ## progress_range by the number of milliseconds
890 ## in the file, then multiply the result by the
891 ## number of milliseconds currently played.
892
893 $data->{progress} =
894 $decoder->{progress} = int(
895 (
896 $self->{options}->{decoder_progress_range} /
897 ($self->{input}->{info}->{s_seconds} * 1000)
898 ) * $ms
899 );
900 }
901
902 ## if any updated data was stashed in our temporary container,
903 ## make sure we generate an event and send that data out..
904
905 $kernel->yield($self->{message_event}, {
906 id => 'DECODER_FRAME_DATA',
907 data => $data
908 }) if (scalar(keys(%{$data})) > 0);
909
910 ## equivalant to: mad_synth_frame(frame);
911
912 $decoder->{synth}->synth($decoder->{frame});
913
914 ## then we gather up the pcm audio for this
915 ## frame.. this requires us to run the samples
916 ## through Audio::Mad::Dither.. and potentially
917 ## Audio::Mad::Resample -- that's all automatically
918 ## handled right here..
919  
920 my $pcm = $decoder->{dither}->dither(
921 defined($decoder->{resample})
922 ? $decoder->{resample}->resample($decoder->{synth}->samples())
923 : $decoder->{synth}->samples()
924 );
925
926 ## immediately do another frame if we currently in the
927 ## process of seeking. once the seek counter hits
928 ## zero, we will resume normal mode of operation..
929
930 redo FRAME if ($decoder->{seeking} && $decoder->{seeking}--);
931  
932 ## we did it! write that pcm data out to the
933 ## dsp..
934  
935 syswrite($self->{output}->{handle}, $pcm);
936 }
937
938 ## make sure we get called again..
939
940 $kernel->yield('__d_decoder_cycle');
941 }
942  
943 sub __d_output_open {
944 my ($self, $kernel, $session, $cycle) = @_[OBJECT, KERNEL, SESSION, ARG0];
945 my $output = $self->{output};
946  
947 ## skip it if we are already open..
948
949 return undef if ($output->{state} eq 'OPEN');
950
951 my ($handle, $mixer);
952
953 ## try to open up the dsp device itself..
954
955 CORE::open($handle, ">$output->{device}") || do {
956 $kernel->yield($self->{message_event}, {
957 id => 'DSP_OPEN_FAILED',
958 data => "failed to open $output->{device}: $!"
959 });
960 return undef;
961 };
962
963 ## try to get a mixer device.. I think we can a bit more
964 ## gracefully if this dosen't work..
965
966 CORE::open($mixer, "+<$output->{mixer_device}") || do {
967 $kernel->yield($self->{message_event}, {
968 id => 'DSP_OPEN_FAILED',
969 data => "failed to open $output->{mixer_device}: $!"
970 });
971 };
972
973 ## do the things necessary to setup a modern dsp
974 ## device.. generate events if anything dosen't
975 ## work as expected..
976
977 dsp_reset($handle) || do {
978 $kernel->yield($self->{message_event}, {
979 id => 'DSP_OPEN_FAILED',
980 data => "failed to reset $output->{device}: $!"
981 });
982 return undef;
983 };
984
985 ## fix: we're still making x86 linux centric decisions here..
986 ## this needs to be better configured. perhaps just adding
987 ## in an output_? option to PCAM would do..
988
989 set_fmt($handle, AFMT_S16_LE) || do {
990 $kernel->yield($self->{message_event}, {
991 id => 'DSP_OPEN_FAILED',
992 data => "failed to set format on $output->{device}: $!"
993 });
994 return undef;
995 };
996
997 ## set the sample rate or whine about it..
998
999 set_sps($handle, $output->{samplerate}) == $output->{samplerate} || do {
1000 $kernel->yield($self->{message_event}, {
1001 id => 'DSP_OPEN_FAILED',
1002 data => "failed to set samplerate on $output->{device}: failed"
1003 });
1004 return undef;
1005 };
1006
1007 ## figure out if we want stereo or not..
1008  
1009 if ($self->{input}->{state} eq 'OPEN' && $self->{input}->{info}->{s_mode} == 0) {
1010 set_stereo($handle, 0);
1011 } else {
1012 set_stereo($handle, 1);
1013 }
1014  
1015 ## update some internal information..
1016
1017 $output->{handle} = $handle;
1018 $output->{state} = 'OPEN';
1019  
1020 $output->{mixer} = $mixer;
1021 $output->{mixer_volume} = mixer_read($mixer, SOUND_MIXER_VOLUME) & 0x000000ff;
1022 _mixer_update($output);
1023
1024 ## sing to the world about what we have done..
1025
1026 $kernel->yield($self->{message_event}, {
1027 id => 'DSP_OPEN_SUCCESS',
1028 data => $output->{device}
1029 });
1030
1031 $kernel->yield($self->{message_event}, {
1032 id => 'DSP_STATUS_DATA',
1033 data => { state => 'OPEN' }
1034 });
1035
1036 $kernel->yield($self->{message_event}, {
1037 id => 'DSP_MIXER_DATA',
1038 data => {
1039 balance => $output->{mixer_balance},
1040 volume => $output->{mixer_volume},
1041 pcm => $output->{mixer_pcm}
1042 }
1043 });
1044 }
1045  
1046 sub __d_output_close {
1047 my ($self, $kernel, $session) = @_[OBJECT, KERNEL, SESSION];
1048 my $output = $self->{output};
1049  
1050 ## exit out if we have no reason to be here..
1051
1052 return undef unless ($output->{state} eq 'OPEN');
1053
1054 ## attempt to close our dsp device, or issue a
1055 ## warning telling people. (shouldn't /dev/mixer)
1056 ## be closed too?
1057
1058 CORE::close($output->{handle}) || $kernel->yield($self->{message_event}, {
1059 id => 'DSP_CLOSE_WARNING',
1060 data => "failed to close $output->{device}"
1061 });
1062
1063 ## update state..
1064  
1065 $output->{handle} = undef;
1066 $output->{state} = 'CLOSED';
1067
1068 ## tell everyone..
1069
1070 $kernel->yield($self->{message_event}, {
1071 id => 'DSP_CLOSE_SUCCESS',
1072 data => $output->{device},
1073 });
1074
1075 $kernel->yield($self->{message_event}, {
1076 id => 'DSP_STATUS_DATA',
1077 data => { state => 'CLOSED' }
1078 });
1079 }
1080  
1081 ##############################################################################
1082  
1083 ## cheap, cheap utility method to prevent code duplication..
1084 ## and handle a little maths for us.
1085  
1086 sub _mixer_update {
1087 my ($o) = @_;
1088  
1089 ## exit out unless we have reason to work..
1090 return undef unless ($o->{state} eq 'OPEN');
1091  
1092 ## there is no balance, only left and right
1093 ## volumes..
1094 my ($vl, $vr) = ($o->{mixer_volume})x2;
1095 my ($pl, $pr) = ($o->{mixer_pcm})x2;
1096
1097 ## a little algorithm to smoothly scale the volumes
1098 ## off as we adjust the balance. the ear percives
1099 ## volume changes logarithmically, so that's why
1100 ## we do this here.. not that I understand that,
1101 ## I just read a perldoc and a webpage about the Nth
1102 ## log of a number.. let me know if this is stupid,
1103 ## but it works for me..
1104 my $b = 50 - $o->{mixer_balance};
1105 if ($b < 0) { $vl = int($vl * (log(50 + $b + 1)/log(50))) }
1106 elsif ($b > 0) { $vr = int($vr * (log(50 - $b + 1)/log(50))) }
1107
1108 ## actually pump out our new volumes to the
1109 ## mixer device..
1110 mixer_write($o->{mixer}, SOUND_MIXER_PCM, $vl, $vr);
1111 mixer_write($o->{mixer}, SOUND_MIXER_VOLUME, $pl, $pr);
1112 }
1113
1114 ##############################################################################
1115 1;
1116 __END__