DB/Build.pm untested

filter: Statementstmt 0.0% 0 / 241 Branchbran 0.0% 0 / 68 Conditioncond 0.0% 0 / 44 MC/DCmcdc 0.0% 0 / 24 Subroutinesub 0.0% 0 / 26 Podpod 0.0% 0 / 18 totaltotal 0.0% 0 / 421 CC 33 SCAR 28.0
CC
33
Cov
0%
_check_album_mem
42.0
_load_db
42.0
initialize
20.0
CRAP 16.5
1 package Audio::DB::Build;
2  
3 # $Id: Build.pm,v 1.2 2005/02/27 16:56:25 todd Exp $
4 use strict 'vars';
5  
6 use Carp 'croak','cluck';
7 use vars qw(@ISA $VERSION);
8  
9 use Audio::DB;
10 use Audio::DB::Parse::iTunes;
11 use Audio::DB::Parse::FlatFile;
12 use Audio::DB::Parse::ReadFiles;
13 use Audio::DB::Util::Rearrange;
14  
15 my $ENV_TMP = $ENV{TMP} || $ENV{TMP_DIR} || (-d '/tmp') ? '/tmp' : (-d '/var/tmp') ? '/var/tmp' : '';
16  
17 $|++;
18  
19 @ISA = qw/Audio::DB Audio::DB::Util::DataAccess/;
20  
21 $VERSION = '';
22  
23 # Initialize a new database
24 sub initialize {
25 my $self = shift;
26 my $adaptor = $self->adaptor;
27 if (defined $self->{shout}) { print STDERR "Initializing database...\n"; };
28 $adaptor->do_initialize(1) if @_ == 1 && $_[0];
29 my ($erase,$meta) = rearrange(['ERASE'],@_);
30 $meta ||= {};
31
32 # initialize (possibly erasing)
33 return unless $adaptor->do_initialize($erase);
34 # return;
35 1;
36 }
37  
38  
39 # Wrapper method for quickly building a database
40 # I think that much of this code belongs in the adaptor...
41 sub load_database {
42 my ($self,@p) = @_;
43 my ($dirs,$files,$library,$columns,$tmp,$shout,@others) =
44 rearrange([
45 [qw(DIR DIRS TOP_DIRS)],
46 FILES,
47 LIBRARY,
48 COLUMNS,
49 TMP,
50 [qw(VERBOSE YELL SCREAM)],
51 ],@p);
52
53 # Set some system-level variables
54 $tmp ||= $ENV_TMP;
55 $self->{tmp} = $tmp;
56 $self->{shout} = $shout if ($shout);
57  
58 # User has supplied an iTunes library file. Let's parse that.
59 if ($library) {
60 Audio::DB::Parse::iTunes->parse_library($self,$library);
61 } elsif (@$files > 0) {
62 # Parsing information from a flat file of mp3 information
63 Audio::DB::Parse::FlatFile->parse_files($self,$files,$columns);
64 } else {
65 # Reading data directly from MP3z...
66 Audio::DB::Parse::ReadFiles->process_directories($self,$dirs);
67 }
68  
69 my $adaptor = $self->adaptor;
70 $self->_dump_data_structures();
71 $self->_load_db();
72 my $stats = $self->get_stats();
73 return $stats;
74 }
75  
76  
77 # UPDATE DATABASE IS NOT COMPLETELY WORKING YET!!
78 # Wrapper method for quickly adding new songs to a database.
79 # This needs to check within the DB itself for artists
80 # and albums, as well as within the current set.
81 sub update_database {
82 my ($self,@p) = @_;
83 my ($dirs,$files,$columns,$tmp,$shout,@others) =
84 rearrange([
85 [qw(DIR DIRS TOP_DIRS)],
86 FILES,
87 COLUMNS,
88 TMP,
89 [qw(VERBOSE YELL SCREAM)],
90 ],@p);
91
92 # Establish the counters based on preexisitng values in database
93 $self->_establish_counters();
94  
95 if ($files) {
96 Audio::DB::Parse::FlatFile->parse_files($self,$files,$columns);
97 } else {
98 # Reading data directly from MP3z...
99 # Save the top level directory
100
101 @{$self->{top_dirs}} = @{$dirs};
102 $tmp ||= $ENV_TMP;
103 $self->{tmp} = $tmp;
104 $self->{shout} = $shout if ($shout);
105 Audio::DB::Parse::ReadFiles->process_directories($self);
106 }
107  
108 $self->_dump_data_structures();
109 $self->_load_db();
110 return;
111 }
112  
113 sub get_stats {
114 my $self = shift;
115 my $stats = {};
116 $stats->{artists} = $self->{counters}->{artists};
117 $stats->{albums} = $self->{counters}->{albums};
118 $stats->{genres} = $self->{counters}->{genres};
119 $stats->{songs} = $self->{counters}->{songs};
120 return $stats;
121 }
122  
123  
124 # TODO WARNING
125 # This is ONLY used during updates and has not been brought up-to-date.
126 # Get the highest values for each before adding
127 # new info to the DB.
128 # This requires MySQL specific code and should probably be moved...
129 # not documented yet
130 sub _establish_counters {
131 my $self = shift;
132 if (defined $self->{shout}) { print STDERR "Establishing counters...\n"; };
133 my $adaptor = $self->adaptor;
134 my $dbh = $adaptor->dbh();
135 my %fields = (
136 song_id => songs,
137 artist_id => artists,
138 album_id => albums,
139 genre_id => genres);
140
141 foreach (keys %fields) {
142 my $sth = $adaptor->lookup_counter($_,$fields{$_});
143 $sth->execute();
144 my ($id) = $sth->fetchrow_array;
145 $self->{counters}->{$fields{$_}} = $id;
146 }
147 return;
148 }
149  
150 # Caveats -
151 # Singles are either labelled as "singles" or with nothing
152 # Albums of the same name can only be distiniguished if their year and total_tracks
153 # are differnet. If you haven't assigned either of these, you'll have one less
154 # metric for distinguishing albums.
155  
156 # I SHOULD KEEP FULL COLLECTION STATISTICS HERE TOO (
157 # THIS WOULD REQUIRE A NEW TABLE
158  
159 sub cache_song {
160 my ($self,$song) = @_;
161 return if (!$song);
162 my $artist = $song->{artist};
163 my $album = $song->{album};
164
165 # Check to see if we have seen this artist, genre, or album before
166 my $artist_id = $self->_check_artist_mem($artist);
167 my $genre_id = $self->_check_genre_mem($song->{genre});
168 my $album_id = $self->_check_album_mem($song,$artist_id);
169
170 my $id = ++$self->{counters}->{songs};
171
172 if (defined $self->{shout} && ($id % $self->{shout}) == 0) {print_msg("Songs processed : $id") };
173  
174 # Would be nice to generate the song_types join, flagging possible live tracks, covers, etc...
175 $self->{songs}->{$id} = {
176 title => $song->{title},
177 artist_id => $artist_id,
178 album_id => $album_id,
179 genre_id => $genre_id,
180 track => $song->{track},
181 total_tracks => $song->{total_tracks},
182 duration => $song->{duration},
183 seconds => $song->{seconds},
184 bitrate => $song->{bitrate},
185 samplerate => $song->{samplerate},
186 comment => $song->{comment},
187 filename => $song->{filename},
188 filesize => $song->{filesize},
189 filepath => $song->{filepath},
190 tagtypes => $song->{tagtypes},
191 format => $song->{layer},
192 channels => $song->{channels},
193 year => $song->{year}, # normally this is stored with album
194 rating => $song->{rating}, # but could be different for comps
195 playcount => $song->{playcount}
196 };
197
198 # Store some additional information about each album in order
199 # to create artist_album and artist_genre associations
200 # This way I can easily find albums that have more than a single
201 # genre assigned to them
202 $self->{artists}->{$artist_id}->{albums}->{$song->{album}} = $album_id;
203 $self->{artists}->{$artist_id}->{genres}->{$genre_id}++;
204 # Finally, add some additional information to the albums hash
205
206 # This is an easy way of keeping track of compilation CDs -
207 # autoincrement each time I see an artist. Compilations will have multiple keys
208 # I can then flag this album as a compilation if I so desire when dumping the table
209 $self->{albums}->{$album_id}->{contributing_artists}->{$artist_id}++;
210 return;
211 }
212  
213 sub _stuff_album {
214 my ($self,$tag) = @_;
215 my $album_id = ++$self->{counters}->{albums};
216 my $track = $tag->{track};
217 my $tot_tracks = $tag->{total_tracks};
218 $self->{albums}->{$album_id} = { album => $tag->{album},
219 total_tracks => $tot_tracks,
220 year => $tag->{year},
221 };
222 # Store the album in the lookups hash
223 $self->{lookups}->{albums}->{$tag->{album}} = $album_id;
224 return $album_id;
225 }
226  
227  
228 ###############################
229 # Internal methods that check #
230 # if we have seen artist, #
231 # album, or genre yet #
232 ###############################
233 sub _check_artist_mem {
234 my ($self,$artist) = @_;
235 if (defined $self->{lookups}->{artists}->{$artist}) {
236 # There is an artist stored, but perhaps it's a duplicate name?
237 # Need to deal with this somehow...
238 # TO DO: Need to handle artists that have the same name...
239 return $self->{lookups}->{artists}->{$artist};
240 } else {
241 # This is our first encounter
242 # increment the id and return it
243 # Store the artist in the lookup hash and
244 # initialize in the artist hash
245 my $id = ++$self->{counters}->{artists};
246 $self->{lookups}->{artists}->{$artist} = $id;
247 $self->{artists}->{$id} = { artist => $artist };
248 return $id;
249 }
250 }
251  
252 sub _check_genre_mem {
253 my ($self,$genre) = @_;
254 # Genres are unique - they are simple to deal with
255 if (defined $self->{lookups}->{genres}->{$genre}) {
256 return $self->{lookups}->{genres}->{$genre};
257 } else {
258 # If not, enter this genre into the
259 # lookups hash and the corresponding genre hash
260 my $id = ++$self->{counters}->{genres};
261 $self->{lookups}->{genres}->{$genre} = $id;
262 $self->{genres}->{$id} = $genre;
263 return $id;
264 }
265 }
266  
267 sub _check_album_mem {
268 my ($self,$tag,$artist_id) = @_;
269 my $artist = $tag->{artist};
270 my $album = $tag->{album};
271 my $year = $tag->{year};
272 my $track = $tag->{track};
273 my $tot_tracks = $tag->{total_tracks};
274  
275 my $album_id;
276 if (defined $self->{lookups}->{albums}->{$album}) {
277 my $test_id = $self->{lookups}->{albums}->{$album};
278 # 1. Perhaps this is just a "single", not part of an album.
279 # Generally this may be an mp3 that is lacking an album tag
280 # At any rate, I want each song that is either labelled as a single
281 # or is blank to be listed as part of its own album, and not grouped together
282
283 # This should probably be fixed.
284 if ($album =~ /^singles/i) {
285 # Check to see if I've added the singles album to this artist...
286 if (defined $self->{artists}->{$artist_id}->{albums}->{$album}) {
287 $album_id = $self->{artists}->{$artist_id}->{albums}->{$album};
288 } else {
289 # A new album - lets enter it into the object
290 $album_id = $self->_stuff_album($tag);
291 }
292 }
293
294 # 2. Maybe we have just hit two albums with the same name
295 # See if the year and total tracks are the same.
296 # Would be nice to have some other metric of grouping...
297 # File paths, genres, etc...
298 if (!$album_id) {
299 # USING THE YEAR WILL NOT WORK!
300 # Many albums have songs where the years are different!
301 # my $stored_year = $self->{albums}->{$test_id}->{year};
302 my $stored_tracks = $self->{albums}->{$test_id}->{total_tracks};
303 # if ($stored_year != $year || $stored_tracks != $tot_tracks) {
304 if ($stored_tracks != $tot_tracks) {
305 # Aah! A conflict - let's enter a new album!
306 $album_id = $self->_stuff_album($tag);
307 }
308 }
309
310 # If neither of those metrics revealed a discrepancy with the
311 # identified album, then it might just possibly be another track from
312 # a preexisting album.
313 # Set album_id to the temp_id
314 $album_id ||= $test_id;
315 } else {
316 $album_id = $self->_stuff_album($tag);
317 }
318 return $album_id;
319 }
320  
321  
322  
323 ################################################
324 # Temp table generating subs
325 ################################################
326 # Need to make song_genres and song_types;
327 sub _dump_data_structures {
328 my $self = shift;
329 if (defined $self->{shout}) { print STDERR "\nDumping tables...\n"; };
330 $self->_dump_artists();
331 $self->_dump_albums();
332 $self->_dump_genres();
333 $self->_dump_songs();
334 return;
335 }
336  
337  
338 # TODO WARNING
339 # Figure out how to purge this adaptor specific code
340 # I REALLY hate that there is adaptor specific code here
341 # Generate the artists and artist_genres table
342 sub _dump_artists {
343 my $self = shift;
344 my $adaptor = $self->adaptor;
345 my $dbh = $adaptor->dbh;
346 open OUT, ">$self->{tmp}/artists" or die "Couldn't open temporary file: $!";
347 open OUT2,">$self->{tmp}/artist_genres" or die "Couldn't open temporary file: $!";
348 foreach my $artist_id (sort keys %{$self->{artists}}) {
349 my $artist = $self->{artists}->{$artist_id}->{artist};
350 if ($adaptor =~ /sqlite/) {
351 $dbh->do("INSERT INTO artists (artist_id,artist) VALUES (?,?)",undef,($artist_id,$artist));
352 } else {
353 print OUT join("\t",$artist_id,$artist),"\n";
354 }
355 # artist_genre join table
356 foreach my $genre_id (keys %{$self->{artists}->{$artist_id}->{genres}}) {
357 if ($adaptor =~ /sqlite/) {
358 $dbh->do("INSERT INTO artist_genres (artist_id,genre_id) VALUES (?,?)",undef,($artist_id,$genre_id));
359 } else {
360 print OUT2 join("\t",$artist_id,$genre_id),"\n";
361 }
362 }
363 }
364 close OUT;
365 close OUT2;
366 }
367  
368 # Generate the album and album_artists join tables
369 sub _dump_albums {
370 my $self = shift;
371 # Need to open two file handles...
372 # Albums and Album artists
373 open OUT, ">$self->{tmp}/albums" or die "Couldn't open temporary file: $!";
374 open OUT2,">$self->{tmp}/album_artists" or die "Couldn't open temporary file: $!";
375 my $adaptor = $self->adaptor;
376 my $dbh = $adaptor->dbh;
377 foreach my $album_id (sort keys %{$self->{albums}}) {
378 my $album = $self->{albums}->{$album_id}->{album};
379 my $year = $self->{albums}->{$album_id}->{year};
380 my $tot_tracks = $self->{albums}->{$album_id}->{total_tracks};
381 my $type = (scalar keys %{$self->{albums}->{$album_id}->{contributing_artists}} == 1) ? 'standard' : 'compilation';
382
383 # Album table
384 if ($adaptor =~ /sqlite/) {
385 $dbh->do("INSERT INTO albums (album_id,album,type,total_tracks,year) VALUES (?,?,?,?,?)",undef,
386 ($album_id,$album,$type,$tot_tracks,$year));
387 } else {
388 print OUT join("\t",$album_id,$album,$type,$tot_tracks,$year),"\n";
389 }
390 # album_artists join table
391 foreach my $artist_id (keys %{$self->{albums}->{$album_id}->{contributing_artists}}) {
392 if ($dbh =~ /sqlite/) {
393 $dbh->do("INSERT INTO album_artists (artist_id,album,type) VALUES (?,?,?)",undef,
394 ($artist_id,$album,$type));
395 } else {
396 print OUT2 join("\t",$artist_id,$album_id),"\n";
397 }
398 }
399 }
400 close OUT;
401 close OUT2;
402 }
403  
404 # Generate the genre table
405 sub _dump_genres {
406 my $self = shift;
407 my $adaptor = $self->adaptor;
408 my $dbh = $adaptor->dbh;
409 open OUT,">$self->{tmp}/genres" or die "Couldn't open temporary file: $!";
410 foreach my $genre_id (sort keys %{$self->{genres}}) {
411 my $genre = $self->{genres}->{$genre_id};
412 if ($adaptor =~ /sqlite/) {
413 $dbh->do("INSERT INTO genres (genre_id,genre) VALUES (?,?)",undef,($genre_id,$genre));
414 } else {
415 print OUT join("\t",$genre_id,$genre),"\n";
416 }
417 }
418 close OUT;
419 }
420  
421 # Generate the songs table
422 sub _dump_songs {
423 my $self = shift;
424 my $adaptor = $self->adaptor;
425 my $dbh = $adaptor->dbh;
426 open OUT,">$self->{tmp}/songs" or die "Couldn't open temporary file: $!";
427 foreach my $song_id (sort keys %{$self->{songs}}) {
428 my $href = $self->{songs}->{$song_id};
429 if ($adaptor =~ /sqlite/) {
430 $dbh->do("INSERT INTO songs (song_id,title,artist_id,album_id,genre_id,track,duration,seconds,lyrics,comment,bitrate,samplerate,fileformat,channels,tagtypes,filename,filesize,filepath,year,rating,playcount,dateadded,datemodified) VALUES (?,?,?,?,?,?
431 ,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",undef,
432 ($song_id,
433 $href->{title},
434 $href->{artist_id},
435 $href->{album_id},
436 $href->{genre_id},
437 $href->{track},
438 $href->{duration},
439 $href->{seconds},
440 $href->{lyrics},
441 $href->{comment},
442 $href->{bitrate},
443 $href->{samplerate},
444 $href->{format},
445 $href->{channels},
446 $href->{tagtypes},
447 $href->{filename},
448 $href->{filesize},
449 $href->{filepath},
450 $href->{year},
451 $href->{rating},
452 $href->{playcount},
453 $href->{dateadded} || '\N',
454 $href->{datemodified} || '\N',));
455 } else {
456 print OUT join("\t",$song_id,
457 $href->{title},
458 $href->{artist_id},
459 $href->{album_id},
460 $href->{genre_id},
461 $href->{track},
462 $href->{duration},
463 $href->{seconds},
464 $href->{lyrics},
465 $href->{comment},
466 $href->{bitrate},
467 $href->{samplerate},
468 $href->{format},
469 $href->{channels},
470 $href->{tagtypes},
471 $href->{filename},
472 $href->{filesize},
473 $href->{filepath},
474 $href->{year}, # Denormalization to account for compilation CDs
475 $href->{rating},
476 $href->{playcount}
477 ),"\n";
478 }
479 }
480 close OUT;
481 }
482  
483 # TODO WARNING
484 # Figure out how to purge this adaptor specific code
485 sub _load_db {
486 my $self = shift;
487  
488 if (defined $self->{shout}) { print STDERR "Loading tables...\n" };
489 # Fetch the table names
490 my $adaptor = $self->adaptor;
491 my @tables = $adaptor->tables;
492 my $dbh = $adaptor->dbh;
493 my $tmp = $self->{tmp};
494 foreach (@tables) {
495 if (-e "$tmp/$_") {
496 if ($adaptor =~ /sqlite/) {
497 # SQLite does not support infile loads, apparently. Bummer.
498 } elsif ($adaptor =~ /mysql/) {
499 # $dbh->do("lock tables $_ write; delete from $_; load data infile '$tmp/$_' replace into table $_; unlock tables");
500 if (defined $self->{shout}) { print STDERR "loading table $_...\n"; }
501 $dbh->do("load data infile '$tmp/$_' replace into table $_") or warn "COULDN'T LOAD TABLE $_";
502 } else {};
503 }
504 unlink "$self->{tmp}/$_";
505 }
506 }
507  
508  
509 sub get_couldnt_read {
510 my $self = shift;
511 my @couldnt = @{$self->{couldnt_read}};
512 return \@couldnt;
513 }
514  
515  
516 sub print_msg {
517 my $msg = shift;
518 print STDERR $msg;
519 print STDERR -t STDOUT && !$ENV{EMACS} ? "\r" : "\n";
520 }
521  
522 1;
523  
524 =pod
525  
526 =head1 NAME
527
528 Audio::DB - Tools for generating relational databases of MP3s
529
530 =head1 SYNOPSIS
531  
532 use Audio::DB;
533 my $mp3 = Audio::DB->new(-user =>'user',
534 -pass =>'password',
535 -host =>'db_host',
536 -dsn =>'music_db',
537 -adaptor => 'mysql');
538  
539 $mp3->initialize(1);
540  
541 $mp3->load_database(-dirs =>['/path/to/MP3s/'],
542 -tmp =>'/tmp');
543  
544 =head1 DESCRIPTION
545  
546 Audio::DB is a module for creating relational databases of MP3 files
547 directly from data stored in ID3 tags or from flatfiles of information
548 of track information. Once created, Audio::DB provides various methods
549 for creating reports and web pages of your collection. Although it's
550 nutritious and delicious on its own, Audio::DB was created for use with
551 Apache::Audio::DB, a subclass of Apache::MP3. This module makes it easy
552 to make your collection web-accessible, complete with browsing,
553 searching, streaming, multiple users, playlists, ratings, and more!
554  
555 =head1 REQUIRES
556
557 B<MP3::Info> for reading ID3 tags, B<LWP::MediaTypes> for distinguising
558 types of readable files;
559  
560 =head1 EXPORTS
561
562 No methods are exported.
563
564 =head1 CAVEATS
565  
566 Metrics for assigning songs to albums:
567 Since Audio::DB processes file-by-file, it uses a number of parameters to assign
568 tracks to albums. The quality of the results of Audio::DB will depend directly
569 on the quality and integrity of the ID3 tags of your files.
570  
571 Single tracks (those not belonging to a specific album) are distinguished by
572 either undef or the label "single" in the album tag. In this way, all the single tracks
573 for a given artist can be easily grouped together and fetched as a sort of
574 pseudo-album. Of course, since you've ripped all of your MP3z from albums that you own,
575 this shouldn't be a problem ;).
576  
577 If two or more albums have the same name ("Greatest Hits"), Audio::DB checks
578 to see if the year they were released and the total number of tracks is the same.
579 If so, it thinks they are the same album, and all tracks are grouped together.
580 This works most of the time, but obviously will fail sometimes. If you haven't
581 assigned either of these tags, you'll have one less metric for distinguishing
582 tracks. If you have a better metric for distinguishing tracks, please let me know!
583  
584 =head1 METHODS
585  
586 =head2 initialize
587  
588 Title : initialize
589 Usage : $mp3->initialize(-erase=>$erase);
590 Function: initialize a new database
591 Returns : true if initialization successful
592 Args : a set of named parameters
593 Status : Public
594  
595 This method can be used to initialize an empty database. It takes the following
596 named arguments:
597  
598 -erase A boolean value. If true the database will be wiped clean if it
599 already contains data.
600  
601 A single true argument ($mp3->initialize(1) is the same as initialize(-erase=>1).
602 Future versions may support additional options for initialization and database
603 construction (ie custom schemas).
604  
605 =head2 load_database
606  
607 Title : load_database
608 Usage :
609  
610 Creating a database by reading the tags from MP3 files:
611 $stats = $mp3->load_database(-dirs => ['/path/to/MP3s/'],
612 -tmp => '/tmp',
613 -verbose => 100);
614  
615 Creating a database from a flat file of file information
616 : $stats = $mp3->load_database(-files => ['/path/to/files/'],
617 -columns => '[columns in file]',
618 -tmp => '/tmp',
619 -verbose => 100);
620  
621 Creating a database from the iTunes Music Library.xml file
622 $stats = $mp3->load_database(-library => '/path/to/iTunes\ Music\ Library.xml',
623 -verbose => 100);
624  
625 Function: Parses mp3s and loads database
626 Returns : Hash reference containing number of artists, albums, songs,
627 and genres processed.
628 Args : array of top-level paths to mp3s; path to tmp directory,
629 verbose flag
630 Status : Public
631  
632 load_database is a broad wrapper method that provides simplified
633 access to many Audio::DB less-public methods. load_database expects an
634 array of top level paths to directories containing MP3s to load. The
635 second required parameter is the path to a suitable /tmp directory.
636 Audio::DB::Build will write temporary files to this directory prior to doing
637 bulk loads into the database.
638  
639 The optional -verbose flag will a variety of messages to be displayed
640 to STDERR during processing. The value of -verbose controls how
641 frequently to display a message during song processing.
642  
643 Instead of reading the tags directly, a flat file or files containing
644 the ID3 tag information can be read. This is particularly useful, in
645 part for offline files that have been cataloged with utilities like
646 MP3Rage. Furthermore, I've found that the MP3::Info modules that
647 Audio::DB::Build relies on isn't as robust at reading tags as other
648 applications. The path to individual files or directories contain
649 batches of these files should be passed in as an anonymous array. A
650 second parameter, columns, should also be passed showing the order of
651 the fields in the file. Minimally, the file should contain album,
652 artist, and title. The following column names should be adhered to:
653  
654 title => song title
655 artist => performing artist
656 album => containing album
657 track => song track number
658 total_tracks => total tracks on album
659 duration => [optional] formatted string of song duration
660 seconds => [optional] song duration in seconds
661 bitrate => [optional] integer. The bitrate of the song
662 samplerate => [optional] sample rate of encoding
663 comment => [optional] song comment
664 filename => [optional] duh.
665 filesize => [optional] file size in kb
666 filepath => [optional] absolute file path
667 tagtypes => [optional] ID3 tag types present
668 fileformat => [optional] file format
669 channels => [optional] number of channels
670 year => [optional] year of the album
671 rating => [optional] user rating
672 playcount => [optional] song play count
673 playdate => [optional] date song last played
674 dateadded => [optional] date song added to collection
675 datemodified => [optional] date song information last modified
676  
677 =head2 update_database
678  
679 Title : update_database
680 Usage : $mp3->update_database(-dirs =>['/path/to/MP3s/'],
681 -tmp =>'/tmp',
682 -verbose => '/100/');
683  
684 $mp3->update_database(-files =>['/path/to/files'],
685 -columns =>'[columns in file]',
686 -tmp =>'/tmp',
687 -verbose => 100);
688  
689 Function: Parses new mp3s and adds them to a pre-existing database,
690 Returns : true if succesful
691 Args : array of top-level paths to new mp3s; path to tmp directory
692 Status : Public
693
694 <B>update_database<B> accepts the same parameters and is a similar in
695 function to load_database except that it takes a path to new mp3s and
696 adds them to a preexisting database. The artist and album of these
697 new files will be checked against those already existing in the
698 database to prevent addition of duplicates. Duplicate songs, however,
699 will be added. This is a feature, since you may want multiple copies
700 of some tracks. It's up to you in advance to remove duplicates if you
701 don't want them listed in your database. See the section below
702 "Appending To A Preexisting Database" for more information on using
703 this method.
704  
705 The optional -verbose flag will a variety of messages to be displayed
706 to STDERR during processing. The value of -verbose controls how
707 frequently to display a message during song processing.
708  
709 Like load_database, update_database can read information directly from
710 flat files instead of the MP3s themselves. See load_database for more
711 information.
712  
713 =head1 Additional Public Methods
714  
715 Audio::DB;:Build contains several additional public methods that you are
716 welcome to use if you'd like greater control over file parsing and
717 database loading. In the normal course of things, you probably will
718 not need to use these methods directly but are described for
719 completeness.
720  
721 =head2 cache_song
722  
723 Title : cache_song
724 Usage : $mp3->cache_song(-full_path=>$full_path,-file=>$file);
725 $mp3->cache_song(-song=>$song);
726 Function: Parses new mp3s and adds them to a pre-existing database
727 Returns : true if successful
728 Args : a pre-processed data hash arising from one of the Parse modules
729 Status : Public
730  
731 cache_song accepts the filename and full path to a file to be
732 processed. It makes seperate calls to MP3::Info to extract ID3 tag
733 info. Once extracted, song information is checked against the database
734 to determine if the artist or album have been seen before, adding the
735 song to that artist or album or inserting new artists / albums into
736 the internal temporary data structure as required. Finally, the song
737 is added to this structure.
738  
739 Alternatively, cache_song can be passed a single tab-delimited line of
740 data that holds the relevant information. See load_database for more
741 information and using this interface.
742  
743 =head2 get_couldnt_read
744  
745 Title : get_couldnt_read
746 Usage : $mp3->get_couldnt_read()
747 Function: Fetch a list of files that could not be read
748 Returns : Array reference of files whose tags could not be read
749 Args : none
750 Status : Public
751  
752 =head2 get_stats
753  
754 Title : get_stats
755 Usage : $mp3->get_stats;
756 Function: Get some info on files loaded
757 Returns : Hash reference containing the number of artists,
758 albums, genres, and songs loaded into the database.
759 Args : none
760 Status : Public
761  
762 =head1 Private Methods
763  
764 There are a number of private methods, described here for my own sanity.
765 These methods are not part of the public interface.
766  
767 =head2 _establish_counters
768  
769 Title : _establish_counters
770 Usage : $mp3->_establish_counters
771 Function: Used to determine the highest values for keys before adding
772 new data to the database.
773 Returns : Hash reference containing the number of artists,
774 albums, genres, and songs loaded into the database.
775 Args : none
776 Status : Private
777  
778 =head2 get_tags
779  
780 Title : get_tags
781 Usage : $mp3->get_tags(@args);
782 Function: Fetch and processes raw ID3 tags from files
783 Returns : Hash reference of parsed tag data
784 Status : Private
785  
786 =head2 _check_*_mem, _check_*_db
787  
788 _check_artist_mem _check_album_mem
789 _check_genre_mem _check_artist_db
790 _check_album_db _check_genre_db
791  
792 Title : _check_*_mem or _check_*_db
793 Usage : $mp3->_check_album_mem($artist);
794 Function: Checks for the existence of the current tag
795 Returns : ID of the appropriate album, artist, genre, if it already exists
796 Args : artist, album, or genre, as appropriate
797 Status : Private
798  
799 The _check_* methods check for the pre-existence of the current
800 artist, album, or genre for the file currently being examined. The two
801 variations, *_mem and *_db, control whether this look up is done
802 against the internal data structure in memory or against a
803 pre-existing database.
804  
805 _check_album_* is necessarily more complex. It attempts to assign
806 songs to albums based on both the year and total number of tracks. See
807 "Caveats" above for more information.
808  
809 =head2 _dump_data_structures
810  
811 Title : _dump_data_structures
812 Usage : _dump_data_structures
813 Function: Wrapper around all the _dump_* subroutines
814 Returns : true if succesful
815 Args : none
816 Status : Private
817  
818 =head2 _dump_*
819  
820 _dump_artists _dump_albums
821 _dump_songs _dump_genres
822  
823 Title : _dump_*
824 Usage : _dump_artists()
825 Function: Create temp files for loading into the database
826 Returns : true if succesful
827 Args : none
828 Status : Private
829  
830 These methods dump out the appropriate data from the internal data
831 structure into the temporary directory path. Some dump multiple tables:
832  
833 _dump_artists : artists and artist_genres tables
834 _dump_albums : album and album_artists tables
835 _dump_songs : songs table
836 _dump_genres : genres table
837  
838 =head2 _load_db
839  
840 Title : _load_db
841 Usage : _load_db()
842 Function: Loads data from temporary tables into the database
843 Returns : true if succesful
844 Args : none
845 Status : Private
846  
847 =head2 _stuff_album
848  
849 Title : _stuff_album
850 Usage : _stuff_album()
851 Function: Stuffs the current album into the internal data structure
852 Returns : true if succesful
853 Args : none
854 Status : Private
855  
856 =head1 Internal Data Structure
857  
858 Audio::DB::Build builds a large internal data structure as it reads each file.
859 The data strucutre is:
860  
861 Lookups - For quick lookups to see if an artist, album or genre has been encountered
862 $self->{lookups}->{artists}->{$artist} = $artist_id;
863 $self->{lookups}->{albums}->{$album} = $album_id;
864 $self->{lookups}->{songs}->{$song} = $song_id;
865 $self->{lookups}->{songs}->{$genre} = $genre_id;
866  
867 Counters - for tracking the number of artists, albums, songs, and genres
868 $self->{counters}->{artists}= $total;
869 $self->{counters}->{albums} = $total;
870 $self->{counters}->{songs} = $total;
871 $self->{counters}->{genres} = $total;
872  
873 $self->{couldnt_read} = [ files that could not be read ];
874  
875 The main data structure of artists, albums, songs, and genres
876 I know, I know, its partially denormalized.
877  
878 $self->{artists}->{$artist_id} = { artist => artist name,
879 genres => { $genre_ids => total },
880 albums => { $album => $album_id }
881 };
882  
883 $self->{albums}->{$album_id} = { album => $album,
884 # For tracking multiple genres per album
885 genres => { $genre_ids => ++ },
886 # For tracking multiple artists per album (compilation CDs)
887 contributing_artists => { $artist_id => ++ },
888 # Internal measure for distinguishing same-named albums
889 total_tracks => total number of tracks,
890 year => year released
891 };
892  
893 $self->{songs}->{$song_id} = { title => song title,
894 artist_id => artist_id,
895 album_id => album_id,
896 genre_id => genre_id,
897 track => track number,
898 total_tracks => total tracks on album,
899 duration => formatted duration,
900 seconds => raw seconds,
901 bitrate => song bitrate,
902 samplerate => sample rate,
903 comment => id3 comment,
904 filename => filename,
905 filesize => filesize,
906 filepath => filepath,
907 tagtypes => types of ID3 tags found,
908 format => MPEG layer,
909 channels => stereo / mono / joint,
910 song_year => year (also with album),
911 rating => user rating,
912 playcount => play count }
913  
914 $self->{genres}->{$genre_id} = { genre => $genre }
915  
916 =head1 BUGS
917  
918 This module implements a fairly complex internal data structure,
919 which in itself rests upon lots of things going right, like reading ID3 tags,
920 tag naming conventions, etc. On top of
921 that, I wrote this in a Starbucks full of screaming children.
922  
923  
924 =head1 TODO
925  
926 Need a resonable way of dealing with tags that can't be read
927  
928 Lots of error checking needs to be added. Support for custom data schemas,
929 including new data types like more extensive artist info, paths to images,
930 etc.
931  
932 Keep track of stats for updates.
933 Fix update - needs to use mysql (these are the _check_artist_db routines that
934 all need to be implemented)
935  
936 Robusticize new for different adaptor types
937  
938 Add in full MP4 support
939 make the data dumps rely on the schema in the module
940 put the schema into its own module
941  
942 =head1 AUTHOR
943  
944 Copyright 2002-2004, Todd W. Harris <harris@cshl.org>.
945  
946 This module is distributed under the same terms as Perl itself. Feel
947 free to use, modify and redistribute it as long as you retain the
948 correct attribution.
949  
950  
951 =head1 ACKNOWLEDGEMENTS
952  
953 Chris Nandor <pudge@pudge.net> wrote MP3::Info, the module responsible for
954 reading MP3 tags. Without, this module would be a best-selling pulp
955 romance novel behind the gum at the grocery store checkout. Chris has
956 been really helpful with issues that arose with various MP3 tags from
957 different taggers. Kudos, dude!
958  
959 Lincoln (Dr. Leichtenstein) Stein <lstein@cshl.org> wrote much of the original
960 adaptor code as part of the l<Bio::DB::GFF> module. Much of that code is
961 incorporated here, albeit in a pared-down form. The code for reading ID3 tags
962 from files only with appropriate MIME-types is borrowed from his <Apache::MP3>
963 module. This was a much more elegant than my lame solution of checking for .mp3!
964 Lincoln tolerates having me in his lab, too, even though I use a Mac.
965  
966 =head1 SEE ALSO
967  
968 L<Audio::DB::Adaptor::dbi::mysql>,L<Audio::DB::Util::Reports>,
969 L<Apache::MP3>, L<Apache::Audio::DB>,L<MP3::Info>
970  
971 =cut