blib/lib/Linux/CDROM/Cookbook.pm untested

filter: Statementstmt n/a Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub n/a Podpod n/a SCAR -
1 package Linux::CDROM::Cookbook;
2 1;
3  
4 =pod
5  
6 =head1 NAME
7  
8 Linux::CDROM cookbook - common recipes featuring your CDROM drive as its main ingredient
9  
10 =head1 DESCRIPTION
11  
12 There's a gazillion ways of reading the disc inside your CDROM drive. The most
13 high-level ones would be mounting your CD and using it as a normal directory or
14 - in case of an Audio-CD - using a player to play tracks. This is boring stuff
15 and you don't need C<Linux::CDROM> for any of that.
16  
17 But when you want to write your own CD-player or -grabber, this is more like
18 it. You can even get at a lower level than that.
19  
20 =head1 PLAYING AUDIO
21  
22 C<Linux::CDROM> offers a couple of methods dealing with that. For starting
23 playback, you will use either C<Linux::CDROM::play_ti> (ti == B<t>rack
24 B<i>ndex) or C<Linux::CDROM::play_msf> (msf == B<m>inute, B<s>econd and
25 B<f>rame).
26  
27 All playing operations happen non-blockingly. That means, you start playback
28 and your program does not wait till the playback is done. Instead if will
29 proceed with the next line.
30  
31 =over 4
32  
33 =item * B<Recipe 1>: I<Playing all tracks on a CD one after the other>
34  
35 use Linux::CDROM;
36
37 my $cd = Linux::CDROM->new("/dev/cdrom")
38 or die $Linux::CDROM::error;
39  
40 $cd->play_msf( Linux::CDROM::Addr->new(CDROM_LBA, 0),
41 Linux::CDROM::Addr->new(CDROM_LBA, $cd->num_frames) );
42  
43 Since we want to play from the beginning to the end, we don't care about any
44 minute, second or frame and so it's most convenient to start with frame 0 and
45 end with the last one (as returned by C<$cd-E<gt>num_frames>.
46  
47 Z<>
48  
49 =item * B<Recipe 2>: I<Playing particular tracks>
50  
51 use Linux::CDROM:
52
53 my $cd = Linux::CDROM->new("/dev/cdrom")
54 or die $Linux::CDROM::error;
55  
56 $cd->play_ti( -from => 2, -to => 4 );
57  
58 As you can see, C<$cd-E<gt>play_ti> is the right tool when you want to access
59 the data track-wise. For playing back just one track, make sure that the value
60 of I<-from> and I<-to> are the same.
61  
62 Z<>
63  
64 =item * B<Recipe 3>: I<Playing a range on the CD>
65  
66 use Linux::CDROM:
67
68 my $cd = Linux::CDROM->new("/dev/cdrom")
69 or die $Linux::CDROM::error;
70  
71 my $start = Linux::CDROM::Addr->new( CDROM_MSF, 0, 1, 0 );
72 my $end = Linux::CDROM::Addr->new( CDROM_MSF, 10, 10, 0);
73  
74 $cd->play_msf( $start, $end );
75  
76 The above will play the first 10 minutes and 10 seconds of the audio. Note that
77 the numbering of minutes begins with 0 whereas seconds always start at 1.
78  
79 Z<>
80  
81 =item * B<Recipe 4>: I<Ask the drive where it is currently playing>
82  
83 You will want to do something similar to that when you want to write your own
84 CD-player. Everyone loves process-counters and -bars:
85  
86 use Linux::CDROM;
87
88 my $cd = Linux::CDROM->new("/dev/cdrom")
89 or die $Linux::CDROM::error;
90  
91 $| = 1;
92
93 # play whole CD again
94 $cd->play_msf( Linux::CDROM::Addr->new(CDROM_LBA, 0),
95 Linux::CDROM::Addr->new(CDROM_LBA, $cd->num_frames) );
96  
97 my $frames = $cd->num_frames;
98 while () {
99 my $poll = $cd->poll;
100
101 break if $poll->status != CDROM_AUDIO_PLAY;
102
103 my $track = $poll->track;
104 my $absaddr = $poll->abs_addr;
105 my $reladdr = $poll->rel_addr;
106
107 printf "\r%02i:%02i:%02i of track %02i |", $reladdr->as_msf, $track;
108 my $offset = int($absaddr->addr->as_lba / $frames * 30);
109 print "-" x $offset, ">", " " x (30 - $offset), "|";
110 }
111  
112 The above will produce an output similar to
113  
114 03:12 of track 02 |--------------> |
115  
116 and will update it constantly. The progress-bar indicates the total amount of
117 audio played of the whole CD whereas the time-counter shows the position in the
118 current track.
119  
120 =item * B<Recipe 5>: I<Pausing, resuming etc. of playback>
121  
122 Since both C<Linux::CDROM::play_msf> and C<Linux::CDROM::play_ti> work
123 non-blockingly, you can easily defer playback with the C<Linux::CDROM::pause>,
124 C<Linux::CDROM::stop> and continue it with C<Linux::CDROM::resume>:
125
126 use Linux::CDROM;
127 use Term::ReadKey;
128
129 my $cd = Linux::CDROM->new("/dev/cdrom")
130 or die $Linux::CDROM::error;
131
132 ReadMode 'raw';
133
134 $cd->play_ti( -from => 1, -to => 8 );
135
136 {
137 while (not defined (my $key = ReadKey(-1))) {
138 print "\r", get_status();
139 select undef, undef, undef, 0.2;
140 }
141 $cd->pause if $key eq 'p';
142 $cd->resume if $key eq 'r';
143 $cd->stop and last if $key eq 's';
144 last if $key eq 'q';
145
146 redo;
147 }
148
149 ReadMode 'restore';
150  
151 sub get_status {
152 my $poll = $cd->poll;
153 my $track = $poll->track;
154 my ($min, $secs) = $poll->rel_addr->as_msf;
155 return sprintf "Track %02i at [%02i:%02i]", $track, $min, $secs;
156 }
157  
158 The above is actually already a useable little CD-player. It updates its status
159 and can be controlled through single key-strokes 'p', 'r', 's' and 'q'. When
160 hitting 'q' the CD will keep playing.
161  
162 All events are processed in two nested infinite loops.
163  
164 =item * B<Recipe 6>: I<A forking player>
165  
166 The program in B<Recipe 5> can also be written using C<fork>. In the case of
167 C<Linux::CDROM> this is actually quite an attractive approach since you may
168 create an object in both your parent and your child process and access them in
169 both. That means that your two processes do not need to be connected through
170 pipes or so.
171  
172 use Linux::CDROM;
173 use Term::ReadKey;
174  
175 my $cd = Linux::CDROM->new( "/dev/cdrom" )
176 or die $Linux::CDROM::error;
177  
178 my $child = fork;
179 if (! defined $child) {
180 die "Oups, couldn't fork: $!";
181 } elsif ($child) {
182 parent();
183 } else {
184 child();
185 }
186  
187 sub parent {
188 $cd->play_ti( -from => 1, -to => 8 );
189 ReadMode 'raw';
190 {
191 my $key;
192 while (not defined ($key = ReadKey(-1))) {
193 # do nothing this time: child handles status display
194 select undef, undef, undef, 0.2;
195 }
196 $cd->pause if $key eq 'p';
197 $cd->resume if $key eq 'r';
198 $cd->stop if $key eq 's';
199 if ($key eq 'q') {
200 kill HUP => $child; # tell our child that we quit
201 wait; # wait for it
202 ReadMode 'restore';
203 exit;
204 }
205 redo;
206 }
207 }
208
209 sub child {
210 $SIG{ HUP } = sub { exit };
211 $| = 1;
212 my $cd = Linux::CDROM->new("/dev/cdrom");
213 while () {
214 my $poll = $cd->poll;
215 my $track = $poll->track;
216 my ($min, $secs) = $poll->rel_addr->as_msf;
217 printf "\rTrack %02i at [%02i:%02i]", $track, $min, $secs;
218 select undef, undef, undef, 0.2;
219 }
220 }
221  
222 The only message that can be exchanged between parent process and child is
223 I<sighup> which the parent process will send when it quits. The child has
224 installed a handler for this signal in C<$SIG{ HUP }>.
225  
226 =item * B<Recipe 7>: I<Length of the last track>
227  
228 For calculating the length of a given track I<i>, you'd usually substract the
229 address of track of track I<i> from the address of track I<i+1>. However, you
230 cannot do this for the last track since there is no such I<i+1> in this case.
231  
232 Every CD (even non-Audio CDs) have a special track called I<Leadout> which is
233 always the last physical track on a CD. It has the index C<CDROM_LEADOUT> which
234 is usually defined to be C<0xAA>. That means that you have to substract the
235 address of the last track from the address of the Leadout track:
236  
237 use Linux::CDROM:
238
239 my $cd = Linux::CDROM->new("/dev/cdrom")
240 or die $Linux::CDROM::error;
241  
242 my ($first, $last) = $cd->toc;
243 $last = $last - $first + 1;
244  
245 my $length = $cd->toc_entry(CDROM_LEADOUT)->addr -
246 $cd->toc_entry($last)->addr;
247  
248 printf "Length of track $track: %i frames", $length->as_lba;
249  
250 =back
251  
252 =head1 GRABBING AUDIO
253  
254 Grabbing audio data happens through C<Linux::CDROM::read_audio>. It returns a
255 string of I<CD_FRAMESIZE_RAW> bytes. These data are simply PCM-encoded samples
256 as you find them in WAV files.
257  
258 However, simply dumping these data to a file wont give you a playable WAV file.
259 The file is lacking an appropriate WAV header that would tell your player how
260 to interpret the PCM-data (as for number of channels, bitrate,
261 sampling-frequency). C<Linux::CDROM> contains the static method
262 C<Linux::CDROM::Format-E<gt>wav_header> to write a header suitable for these
263 PCM data.
264  
265 =over 4
266  
267 =item * B<Recipe 8>: I<Making a WAV file from an Audio track>
268  
269 The WAV header is the first thing in a WAV file, but in this recipe we will
270 write it after grabbing the data to get the byte-count of the data right. We'll
271 leave a hole at the beginning of the file large enough to hold the header:
272  
273 use Linux::CDROM:
274 use Fcntl qw/:seek/;
275  
276 my $cd = Linux::CDROM->new( "/dev/cdrom" )
277 or die $Linux::CDROM::error;
278  
279 my $entry1 = $cd->toc_entry(1);
280 my $entry2 = $cd->toc_entry(2);
281  
282 open WAV, ">track1.wav" or die $!;
283 binmode WAV;
284 # leave room for WAV header (44 bytes)
285 seek WAV, 44, SEEK_SET;
286
287 $cd->reset_datasize:
288
289 for ($entry1->addr->as_lba .. $entry2->addr->as_lba-1) {
290 print WAV $cd->read_audio( Linux::CDROM::Addr->new(CDROM_LBA, $_), 1);
291 }
292  
293 # insert WAV header suitable for this track
294 seek WAV, 0, SEEK_SET;
295 print WAV Linux::CDROM::Format->wav_header( $cd->get_datasize );
296  
297 Note the preliminary call to C<$cd-E<gt>reset_datasize> which resets the
298 internal byte-counter. When grabbing is done (or at any point you wish), the
299 amount of bytes read can be retrieved with C<$cd-E<gt>get_datasize>.
300  
301 After the above you have a valid WAV file with 16bit, 44.1kHz and two channels
302 (stereo).
303  
304 =back
305  
306 =head1 GRABBING DATA
307  
308 The most common scenario is making an ISO-image from a CD. The first thing to
309 understand is that one iso-image doesn't necessarily represent the whole CD.
310 An ISO-image represent always one session on a CD so that only a single-session
311 data CD fits into one image. If you have a multisession CD, you'd create an
312 image for each session.
313  
314 =over 4
315  
316 =item * B<Recipe 9>: I<Making ISO images from a CD>
317  
318 This one collects all data-tracks on the CD and makes an ISO-image out of each:
319  
320 use Linux::CDROM;
321  
322 my $cd = Linux::CDROM->new("/dev/cdrom")
323 or die $Linux::CDROM::error;
324  
325 # collect all data-tracks
326 my @data_tracks;
327 my ($first, $last) = $cd->toc;
328 if ($cd->is_multisession) {
329 foreach ($first .. $last) {
330 push @data_tracks, $_ if $cd->toc_entry($_)->is_data;
331 }
332 }
333  
334 if (! @data_tracks) {
335 die "No grabbable data tracks found";
336 }
337
338 grab_track($_) foreach @data_tracks;
339  
340 sub grab_track {
341 my $track = shift;
342 my $start = $cd->toc_entry($track);
343 my $end = $cd->toc_entry($track == $last ? CDROM_LEADOUT : $track + 1);
344
345 open ISO, ">/tmp/track$track.iso" or die $!;
346 binmode ISO;
347  
348 for ($start->as_lba .. $end->as_lba - 1) {
349 print ISO $cd->read1( Linux::CDROM::Addr->new(CDROM_LBA, $_) );
350 }
351 close ISO;
352 }
353  
354 You can see that this is very similar to grabbing Audio tracks. In both cases
355 you need the start and the end of the track. The result is a file that can be
356 burned onto a CD-R. On a Linux system (and maybe on others as well), you can
357 mount the ISO-image as a regular medium:
358  
359 mount track1.iso /mnt/mountpoint -t iso9660 -o ro,loop=/dev/loop0
360  
361 =back
362  
363 =head1 DOING EVEN MORE
364  
365 C<Linux::CDROM> offers a fairly generous subset of what your kernel permits.
366 There are however a few things not (yet) implemented. For instance,
367 DVD-handling and some of the more obscure things.
368  
369 =over 4
370  
371 =item * B<Recipe 10>: I<Hand-rolling ioctls>
372  
373 This needs a little bit of explanation maybe. This whole module is essentially
374 just a huge pile of ioctl-calls. Everything about a CD is controlled that way.
375 This means that you can achieve the very same functionality this module offers
376 with Perl's C<ioctl>. C<Linux::CDROM> comes with its own C<ioctl> and you should
377 use this instead because it does not require you to create a filehandle. Instead
378 it uses its own.
379  
380 Suppose you don't like C<Linux::CDROM::toc> a lot and instead want to do it by
381 hand. First have a look at your local F<cdrom.h> file. The ioctl you will need is
382  
383 #define CDROMREADTOCHDR 0x5305 /* Read TOC header
384 (struct cdrom_tochdr) */
385  
386 This also tells you that C<struct cdrom_tochdr> is somewhat involved here.
387 This one might look like this:
388  
389 /* This struct is used by the CDROMREADTOCHDR ioctl */
390 struct cdrom_tochdr
391 {
392 __u8 cdth_trk0; /* start track */
393 __u8 cdth_trk1; /* end track */
394 };
395  
396 What you don't know (you have to guess) is that B<CDROMREADTOCHDR> takes no
397 argument but only returns one...through the above C<struct cdrom_tochdr>.
398 Here's the complete code:
399  
400 use Linux::CDROM qw(:all);
401  
402 my $cd = Linux::CDROM->new("/dev/cdrom")
403 or die $Linux::CDROM::error;
404  
405 $cd->ioctl(CDROMREADTOCHDR, my $buf);
406  
407 # result now stored in $buf
408 # need to unpack it accordingly to the C-structure
409  
410 my ($first, $last) = unpack "C C", $buf;
411  
412 The C<unpack> pattern C<"C C"> tells perl to treat the string in C<$buf> as two
413 unsigned char values because C<struct cdrom_tochdr> is a structure of two
414 C<__u8> values.
415
416 The next one is a little more tricky since we also have to pack some arguments
417 into a string. Suppose we want to duplicate
418  
419 my $track = $cd->toc_entry(1);
420  
421 Again the needed parts from C<cdrom.h>:
422  
423 #define CDROMREADTOCENTRY 0x5306 /* Read TOC entry
424 (struct cdrom_tocentry) */
425 ...
426  
427 /* Address in MSF format */
428 struct cdrom_msf0
429 {
430 __u8 minute;
431 __u8 second;
432 __u8 frame;
433 };
434  
435 /* Address in either MSF or logical format */
436 union cdrom_addr
437 {
438 struct cdrom_msf0 msf;
439 int lba;
440 };
441
442 /* This struct is used by the CDROMREADTOCENTRY ioctl */
443 struct cdrom_tocentry
444 {
445 __u8 cdte_track;
446 __u8 cdte_adr :4;
447 __u8 cdte_ctrl :4;
448 __u8 cdte_format;
449 union cdrom_addr cdte_addr;
450 __u8 cdte_datamode;
451 };
452  
453 The tricky part is C<union cdrom_addr cdte_addr>. Since it is a union, it can
454 hold two different values. The two possible types are to be found in C<union
455 cdrom_addr>: It's either a C<struct cdrom_msf0> or an integer.
456  
457 You need to tell your kernel which of these two alternatives you want by setting
458 C<cdrom_tocentry.cdte_format> to either I<CDROM_LBA> or I<CDROM_MSF>.
459  
460 The other real problem with C<struct cdrom_tocentry> is the fact that it
461 contains two bit-fields (two 4-bit wide fields require 1 byte) and that you must
462 consider padding. On most machines, padding happens on 4-byte boundaries. If
463 that is the case, the structure will have these byte offsets if we assume that
464 your integers are 4 bytes wide and that the two bit-fields immediatly follow
465 C<cdte_track> (which is not necessarily the case):
466  
467 byte 0 cdte_track
468 cdte_adr # these two need
469 cdte_ctrl # one byte together
470 cdte_format
471 <padding byte>
472 byte 4 cdte_addr
473 byte 8 cdte_datamode
474  
475 Now that we have figured out a hopefully sane memory layout, we can pack the buffer so that
476 the ioctl hopefully returns the information belonging to track 2 in LBA format. Note that only
477 C<cdte_track> and C<cdte_format> need to be set. All other slots are only used for the return
478 values:
479  
480 my $buf = pack "C # cdte_track
481 C # cdte_adr + cdte_ctrl
482 C # cdte_format
483 x # <padding byte>
484 i # cdte_addr
485 C # cdte_datamode
486 ", 2, 0, CDROM_LBA;
487 $cd->ioctl(CDROMREADTOCENTRY, $buf);
488 my ($track, $adr_ctrl, $format, $lba, $mode) =
489 unpack "CCCxiC", $buf;
490
491 print "Track $track starts at frame $lba";
492  
493 The same in MSF would look like this:
494  
495 my $buf = pack "CCCxCCCxC", 2, 0, CDROM_MSF;
496 $cd->ioctl(CDROMREADTOCENTRY, $buf);
497 my ($track, $adr_ctrl, $format, $min, $sec, $frame, $mode) =
498 unpack "CCCxCCCxC", $buf;
499  
500 The C<"i"> from the LBA example had to be turned into C<"CCCx"> because our union C<cdte_addr>
501
502 union cdrom_addr
503 {
504 struct cdrom_msf0 msf;
505 int lba;
506 };
507
508 now stores the address in the C<msf> slot which looks like this:
509  
510 struct cdrom_msf0
511 {
512 __u8 minute;
513 __u8 second;
514 __u8 frame;
515 };
516  
517 It is three bytes wide, therefore we have another padding byte.
518  
519 =back
520  
521 =head1 SEE ALSO
522  
523 L<Device::CDROM> for a reference to all methods and classes.
524  
525 =head1 AUTHOR
526  
527 Tassilo von Parseval, E<lt>tassilo.von.parseval@rwth-aachen.deE<gt>
528  
529 =head1 COPYRIGHT AND LICENSE
530  
531 Copyright (C) 2004 by Tassilo von Parseval
532  
533 This library is free software; you can redistribute it and/or modify
534 it under the same terms as Perl itself, either Perl version 5.8.2 or,
535 at your option, any later version of Perl 5 you may have available.
536  
537 =cut