v0.19.6
[audio-mpd.git] / lib / Audio / MPD.pm
blob818cf2486a2f81d20667a9818b45e716635ae2f0
2 # This file is part of Audio::MPD
3 # Copyright (c) 2007-2009 Jerome Quelin, all rights reserved.
5 # This program is free software; you can redistribute it and/or modify
6 # it under the same terms as Perl itself.
10 package Audio::MPD;
12 use warnings;
13 use strict;
15 use Audio::MPD::Collection;
16 use Audio::MPD::Common::Item;
17 use Audio::MPD::Common::Stats;
18 use Audio::MPD::Common::Status;
19 use Audio::MPD::Playlist;
20 use Encode;
21 use IO::Socket;
22 use Readonly;
25 use base qw[ Class::Accessor::Fast Exporter ];
26 __PACKAGE__->mk_accessors(
27 qw[ _conntype _host _password _port _socket
28 collection playlist version ] );
31 our $VERSION = '0.19.6';
33 Readonly our $REUSE => 0;
34 Readonly our $ONCE => 1;
36 our @EXPORT = qw[ $REUSE $ONCE ];
39 #--
40 # Constructor
43 # my $mpd = Audio::MPD->new( [%opts] )
45 # This is the constructor for Audio::MPD. One can specify the following
46 # options:
47 # - host => $hostname : defaults to environment var MPD_HOST, then to 'localhost'
48 # - port => $port : defaults to env var MPD_PORT, then to 6600
49 # - password => $password : defaults to env var MPD_PASSWORD, then to ''
50 # - conntype => $type : how the connection to mpd server is handled. it can be
51 # either $REUSE: reuse the same connection
52 # or $ONCE: open a new connection per command (default)
54 sub new {
55 my ($class, %opts) = @_;
57 # use mpd defaults.
58 my ($default_password, $default_host) = split( '@', $ENV{MPD_HOST} )
59 if exists $ENV{MPD_HOST} && $ENV{MPD_HOST} =~ /@/;
60 my $host = $opts{host} || $default_host || $ENV{MPD_HOST} || 'localhost';
61 my $port = $opts{port} || $ENV{MPD_PORT} || '6600';
62 my $password = $opts{password} || $ENV{MPD_PASSWORD} || $default_password || '';
64 # create & bless the object.
65 my $self = {
66 _host => $host,
67 _port => $port,
68 _password => $password,
69 _conntype => exists $opts{conntype} ? $opts{conntype} : $ONCE,
71 bless $self, $class;
73 # create the connection if conntype is set to $REUSE
74 $self->_connect_to_mpd_server if $self->_conntype == $REUSE;
77 # create the helper objects and store them.
78 $self->collection( Audio::MPD::Collection->new($self) );
79 $self->playlist ( Audio::MPD::Playlist->new($self) );
81 # try to issue a ping to test connection - this can die.
82 $self->ping;
84 return $self;
88 #--
89 # Private methods
93 # $mpd->_connect_to_mpd_server;
95 # This method connects to the mpd server. It can die on several conditions:
96 # - if the server cannot be reached,
97 # - if it's not an mpd server,
98 # - or if the password is incorrect,
100 sub _connect_to_mpd_server {
101 my ($self) = @_;
103 # try to connect to mpd.
104 my $socket = IO::Socket::INET->new(
105 PeerAddr => $self->_host,
106 PeerPort => $self->_port,
108 or die "Could not create socket: $!\n";
110 # parse version information.
111 my $line = $socket->getline;
112 chomp $line;
113 die "Not a mpd server - welcome string was: [$line]\n"
114 if $line !~ /^OK MPD (.+)$/;
115 $self->version($1);
117 # send password.
118 if ( $self->_password ) {
119 $socket->print( 'password ' . encode('utf-8', $self->_password) . "\n" );
120 $line = $socket->getline;
121 die $line if $line =~ s/^ACK //;
124 # save socket
125 $self->_socket($socket);
130 # my @result = $mpd->_send_command( $command );
132 # This method is central to the module. It is responsible for interacting with
133 # mpd by sending the $command and reading output - that will be returned as an
134 # array of chomped lines (status line will not be returned).
136 # This method can die on several conditions:
137 # - if the server cannot be reached,
138 # - if it's not an mpd server,
139 # - if the password is incorrect,
140 # - or if the command is an invalid mpd command.
141 # In the latter case, the mpd error message will be returned.
143 sub _send_command {
144 my ($self, $command) = @_;
146 $self->_connect_to_mpd_server if $self->_conntype == $ONCE;
147 my $socket = $self->_socket;
149 # ok, now we're connected - let's issue the command.
150 $socket->print( encode('utf-8', $command) );
151 my @output;
152 while (defined ( my $line = $socket->getline ) ) {
153 chomp $line;
154 die $line if $line =~ s/^ACK //; # oops - error.
155 last if $line =~ /^OK/; # end of output.
156 push @output, decode('utf-8', $line);
159 # close the socket.
160 $socket->close if $self->_conntype == $ONCE;
162 return @output;
167 # my @items = $mpd->_cooked_command_as_items( $command );
169 # Lots of Audio::MPD methods are using _send_command() and then parse the
170 # output as a collection of AMC::Item. This method is meant to factorize
171 # this code, and will parse the raw output of _send_command() in a cooked
172 # list of items.
174 sub _cooked_command_as_items {
175 my ($self, $command) = @_;
177 my @lines = $self->_send_command($command);
178 my (@items, %param);
180 # parse lines in reverse order since "file:" or "directory:" lines
181 # come first. therefore, let's first store every other parameter,
182 # and the last line will trigger the object creation.
183 # of course, since we want to preserve the playlist order, this means
184 # that we're going to unshift the objects instead of push.
185 foreach my $line (reverse @lines) {
186 my ($k,$v) = split /:\s/, $line, 2;
187 $param{$k} = $v;
188 next unless $k eq 'file' || $k eq 'directory' || $k eq 'playlist'; # last param of item
189 unshift @items, Audio::MPD::Common::Item->new(%param);
190 %param = ();
193 return @items;
198 # my %hash = $mpd->_cooked_command_as_kv( $command );
200 # Lots of Audio::MPD methods are using _send_command() and then parse the
201 # output to get a list of key / value (with the colon ":" acting as separator).
202 # This method is meant to factorize this code, and will parse the raw output
203 # of _send_command() in a cooked hash.
205 sub _cooked_command_as_kv {
206 my ($self, $command) = @_;
207 my %hash =
208 map { split(/:\s/, $_, 2) }
209 $self->_send_command($command);
210 return %hash;
214 # my @list = $mpd->_cooked_command_strip_first_field( $command );
216 # Lots of Audio::MPD methods are using _send_command() and then parse the
217 # output to remove the first field (with the colon ":" acting as separator).
218 # This method is meant to factorize this code, and will parse the raw output
219 # of _send_command() in a cooked list of strings.
221 sub _cooked_command_strip_first_field {
222 my ($self, $command) = @_;
224 my @list =
225 map { ( split(/:\s+/, $_, 2) )[1] }
226 $self->_send_command($command);
227 return @list;
232 # Public methods
234 # -- MPD interaction: general commands
237 # $mpd->ping;
239 # Sends a ping command to the mpd server.
241 sub ping {
242 my ($self) = @_;
243 $self->_send_command( "ping\n" );
248 # my $version = $mpd->version;
250 # Return version of MPD server's connected.
252 # sub version {} # implemented as an accessor.
257 # $mpd->kill;
259 # Send a message to the MPD server telling it to shut down.
261 sub kill {
262 my ($self) = @_;
263 $self->_send_command("kill\n");
268 # $mpd->password( [$password] )
270 # Change password used to communicate with MPD server to $password.
271 # Empty string is assumed if $password is not supplied.
273 sub password {
274 my ($self, $passwd) = @_;
275 $passwd ||= '';
276 $self->_password($passwd);
277 $self->ping; # ping sends a command, and thus the password is sent
282 # $mpd->updatedb( [$path] );
284 # Force mpd to rescan its collection. If $path (relative to MPD's music
285 # directory) is supplied, MPD will only scan it - otherwise, MPD will rescan
286 # its whole collection.
288 sub updatedb {
289 my ($self, $path) = @_;
290 $path ||= '';
291 $self->_send_command("update $path\n");
296 # my @handlers = $mpd->urlhandlers;
298 # Return an array of supported URL schemes.
300 sub urlhandlers {
301 my ($self) = @_;
302 return $self->_cooked_command_strip_first_field("urlhandlers\n");
306 # -- MPD interaction: handling volume & output
309 # $mpd->volume( [+][-]$volume );
311 # Sets the audio output volume percentage to absolute $volume.
312 # If $volume is prefixed by '+' or '-' then the volume is changed relatively
313 # by that value.
315 sub volume {
316 my ($self, $volume) = @_;
318 if ($volume =~ /^(-|\+)(\d+)/ ) {
319 my $current = $self->status->volume;
320 $volume = $1 eq '+' ? $current + $2 : $current - $2;
322 $self->_send_command("setvol $volume\n");
327 # $mpd->output_enable( $output );
329 # Enable the specified audio output. $output is the ID of the audio output.
331 sub output_enable {
332 my ($self, $output) = @_;
333 $self->_send_command("enableoutput $output\n");
338 # $mpd->output_disable( $output );
340 # Disable the specified audio output. $output is the ID of the audio output.
342 sub output_disable {
343 my ($self, $output) = @_;
344 $self->_send_command("disableoutput $output\n");
349 # -- MPD interaction: retrieving info from current state
352 # $mpd->stats;
354 # Return an AMC::Stats object with the current statistics of MPD.
356 sub stats {
357 my ($self) = @_;
358 my %kv = $self->_cooked_command_as_kv( "stats\n" );
359 return Audio::MPD::Common::Stats->new(\%kv);
364 # my $status = $mpd->status;
366 # Return an AMC::Status object with various information on current
367 # MPD server settings. Check the embedded pod for more information on the
368 # available accessors.
370 sub status {
371 my ($self) = @_;
372 my %kv = $self->_cooked_command_as_kv( "status\n" );
373 my $status = Audio::MPD::Common::Status->new( \%kv );
374 return $status;
379 # my $song = $mpd->current;
381 # Return an AMC::Item::Song representing the song currently playing.
383 sub current {
384 my ($self) = @_;
385 my ($item) = $self->_cooked_command_as_items("currentsong\n");
386 return $item;
391 # my $song = $mpd->song( [$song] )
393 # Return an AMC::Item::Song representing the song number $song.
394 # If $song is not supplied, returns the current song.
396 sub song {
397 my ($self, $song) = @_;
398 return $self->current unless defined $song;
399 my ($item) = $self->_cooked_command_as_items("playlistinfo $song\n");
400 return $item;
405 # my $song = $mpd->songid( [$songid] )
407 # Return an AMC::Item::Song representing the song with id $songid.
408 # If $songid is not supplied, returns the current song.
410 sub songid {
411 my ($self, $songid) = @_;
412 return $self->current unless defined $songid;
413 my ($item) = $self->_cooked_command_as_items("playlistid $songid\n");
414 return $item;
418 # -- MPD interaction: altering settings
421 # $mpd->repeat( [$repeat] );
423 # Set the repeat mode to $repeat (1 or 0). If $repeat is not specified then
424 # the repeat mode is toggled.
426 sub repeat {
427 my ($self, $mode) = @_;
429 $mode = not $self->status->repeat
430 unless defined $mode; # toggle if no param
431 $mode = $mode ? 1 : 0; # force integer
432 $self->_send_command("repeat $mode\n");
437 # $mpd->random( [$random] );
439 # Set the random mode to $random (1 or 0). If $random is not specified then
440 # the random mode is toggled.
442 sub random {
443 my ($self, $mode) = @_;
445 $mode = not $self->status->random
446 unless defined $mode; # toggle if no param
447 $mode = $mode ? 1 : 0; # force integer
448 $self->_send_command("random $mode\n");
453 # $mpd->fade( [$seconds] );
455 # Enable crossfading and set the duration of crossfade between songs. If
456 # $seconds is not specified or $seconds is 0, then crossfading is disabled.
458 sub fade {
459 my ($self, $value) = @_;
460 $value ||= 0;
461 $self->_send_command("crossfade $value\n");
465 # -- MPD interaction: controlling playback
468 # $mpd->play( [$song] );
470 # Begin playing playlist at song number $song. If no argument supplied,
471 # resume playing.
473 sub play {
474 my ($self, $number) = @_;
475 $number = '' unless defined $number;
476 $self->_send_command("play $number\n");
480 # $mpd->playid( [$songid] );
482 # Begin playing playlist at song ID $songid. If no argument supplied,
483 # resume playing.
485 sub playid {
486 my ($self, $number) = @_;
487 $number ||= '';
488 $self->_send_command("playid $number\n");
493 # $mpd->pause( [$sate] );
495 # Pause playback. If $state is 0 then the current track is unpaused, if
496 # $state is 1 then the current track is paused.
498 # Note that if $state is not given, pause state will be toggled.
500 sub pause {
501 my ($self, $state) = @_;
502 $state ||= ''; # default is to toggle
503 $self->_send_command("pause $state\n");
508 # $mpd->stop;
510 # Stop playback.
512 sub stop {
513 my ($self) = @_;
514 $self->_send_command("stop\n");
519 # $mpd->next;
521 # Play next song in playlist.
523 sub next {
524 my ($self) = @_;
525 $self->_send_command("next\n");
529 # $mpd->prev;
531 # Play previous song in playlist.
533 sub prev {
534 my($self) = shift;
535 $self->_send_command("previous\n");
540 # $mpd->seek( $time, [$song] );
542 # Seek to $time seconds in song number $song. If $song number is not specified
543 # then the perl module will try and seek to $time in the current song.
545 sub seek {
546 my ($self, $time, $song) = @_;
547 $time ||= 0; $time = int $time;
548 $song = $self->status->song if not defined $song; # seek in current song
549 $self->_send_command( "seek $song $time\n" );
554 # $mpd->seekid( $time, [$songid] );
556 # Seek to $time seconds in song ID $songid. If $songid number is not specified
557 # then the perl module will try and seek to $time in the current song.
559 sub seekid {
560 my ($self, $time, $song) = @_;
561 $time ||= 0; $time = int $time;
562 $song = $self->status->songid if not defined $song; # seek in current song
563 $self->_send_command( "seekid $song $time\n" );
571 __END__
573 =pod
575 =head1 NAME
577 Audio::MPD - class to talk to MPD (Music Player Daemon) servers
580 =head1 SYNOPSIS
582 use Audio::MPD;
584 my $mpd = Audio::MPD->new;
585 $mpd->play;
586 sleep 10;
587 $mpd->next;
590 =head1 DESCRIPTION
592 C<Audio::MPD> gives a clear object-oriented interface for talking to and
593 controlling MPD (Music Player Daemon) servers. A connection to the MPD
594 server is established as soon as a new C<Audio::MPD> object is created.
596 Since mpd is still in 0.x versions, C<Audio::MPD> sticks to latest mpd
597 (0.14 as time of writing) protocol & behaviour, and does B<not> try to
598 maintain backward compatibility.
600 Note that the module will by default connect to mpd before sending any
601 command, and will disconnect after the command has been issued. This
602 scheme is far from optimal, but allows us not to care about timeout
603 disconnections. Because of that, the C<idle> command (new in mpd 0.14)
604 is B<not> (and will not) be supported in C<Audio::MPD>. This will be
605 implemented in C<POE::Component::Client::MPD>.
607 B</!\> Note that C<Audio::MPD> is using high-level, blocking sockets.
608 This means that if the mpd server is slow, or hangs for whatever reason,
609 or even crash abruptly, the program will be hung forever in this sub.
610 The C<POE::Component::Client::MPD> module is way safer - you're advised
611 to use it instead of C<Audio::MPD>. Or you can try to set C<conntype> to
612 C<$REUSE> (see C<Audio::MPD> constructor for more details), but you
613 would be then on your own to deal with disconnections.
616 =head1 METHODS
618 =head2 Constructor
620 =over 4
622 =item new( [%opts] )
624 This is the constructor for C<Audio::MPD>. One can specify the following
625 options:
627 =over 4
629 =item host => C<$hostname>
631 defaults to environment var C<MPD_HOST>, then to 'localhost'. Note that
632 C<MPD_HOST> can be of the form password@host.
634 =item port => C<$port>
636 defaults to environment var C<MPD_PORT>, then to 6600.
638 =item password => $password
640 defaults to environment var C<MPD_PASSWORD>, then to ''.
642 =item conntype => $type
644 change how the connection to mpd server is handled. It can be either
645 C<$REUSE> to reuse the same connection or C<$ONCE> to open a new
646 connection per command (default)
648 =back
651 =back
654 =head2 Controlling the server
656 =over 4
658 =item $mpd->ping()
660 Sends a ping command to the mpd server.
663 =item $mpd->version()
665 Return mpd's version number as advertised during connection. Note that
666 mpd returns B<protocol> version when connected. This protocol version
667 can differ from the real mpd version. eg, mpd version 0.13.2 is
668 "speaking" and thus advertising version 0.13.0.
672 =item $mpd->kill()
674 Send a message to the MPD server telling it to shut down.
677 =item $mpd->password( [$password] )
679 Change password used to communicate with MPD server to C<$password>.
680 Empty string is assumed if C<$password> is not supplied.
683 =item $mpd->updatedb( [$path] )
685 Force mpd to recan its collection. If C<$path> (relative to MPD's music
686 directory) is supplied, MPD will only scan it - otherwise, MPD will
687 rescan its whole collection.
690 =item $mpd->urlhandlers()
692 Return an array of supported URL schemes.
695 =back
698 =head2 Handling volume & output
700 =over 4
702 =item $mpd->volume( [+][-]$volume )
704 Sets the audio output volume percentage to absolute C<$volume>. If
705 C<$volume> is prefixed by '+' or '-' then the volume is changed
706 relatively by that value.
709 =item $mpd->output_enable( $output )
711 Enable the specified audio output. C<$output> is the ID of the audio
712 output.
715 =item $mpd->output_disable( $output )
717 Disable the specified audio output. C<$output> is the ID of the audio
718 output.
720 =back
723 =head2 Retrieving info from current state
725 =over 4
727 =item $mpd->stats()
729 Return an C<Audio::MPD::Common::Stats> object with the current statistics
730 of MPD. See the associated pod for more information.
733 =item $mpd->status()
735 Return an C<Audio::MPD::Common::Status> object with various information on
736 current MPD server settings. Check the embedded pod for more information on
737 the available accessors.
740 =item $mpd->current()
742 Return an C<Audio::MPD::Common::Item::Song> representing the song currently
743 playing.
746 =item $mpd->song( [$song] )
748 Return an C<Audio::MPD::Common::Item::Song> representing the song number
749 C<$song>. If C<$song> is not supplied, returns the current song.
752 =item $mpd->songid( [$songid] )
754 Return an C<Audio::MPD::Common::Item::Song> representing the song with id
755 C<$songid>. If C<$songid> is not supplied, returns the current song.
757 =back
760 =head2 Altering MPD settings
762 =over 4
764 =item $mpd->repeat( [$repeat] )
766 Set the repeat mode to C<$repeat> (1 or 0). If C<$repeat> is not
767 specified then the repeat mode is toggled.
770 =item $mpd->random( [$random] )
772 Set the random mode to C<$random> (1 or 0). If C<$random> is not
773 specified then the random mode is toggled.
776 =item $mpd->fade( [$seconds] )
778 Enable crossfading and set the duration of crossfade between songs. If
779 C<$seconds> is not specified or $seconds is 0, then crossfading is
780 disabled.
782 =back
785 =head2 Controlling playback
787 =over 4
789 =item $mpd->play( [$song] )
791 Begin playing playlist at song number C<$song>. If no argument supplied,
792 resume playing.
795 =item $mpd->playid( [$songid] )
797 Begin playing playlist at song ID C<$songid>. If no argument supplied,
798 resume playing.
801 =item $mpd->pause( [$state] )
803 Pause playback. If C<$state> is 0 then the current track is unpaused,
804 if C<$state> is 1 then the current track is paused.
806 Note that if C<$state> is not given, pause state will be toggled.
809 =item $mpd->stop()
811 Stop playback.
814 =item $mpd->next()
816 Play next song in playlist.
819 =item $mpd->prev()
821 Play previous song in playlist.
824 =item $mpd->seek( $time, [$song])
826 Seek to C<$time> seconds in song number C<$song>. If C<$song> number is
827 not specified then the perl module will try and seek to C<$time> in the
828 current song.
831 =item $mpd->seekid( $time, $songid )
833 Seek to C<$time> seconds in song ID C<$songid>. If C<$song> number is
834 not specified then the perl module will try and seek to C<$time> in the
835 current song.
837 =back
840 =head2 Searching the collection
842 To search the collection, use the C<collection()> accessor, returning the
843 associated C<Audio::MPD::Collection> object. You will then be able to call:
845 $mpd->collection->random_song;
847 See C<Audio::MPD::Collection> documentation for more details on available
848 methods.
851 =head2 Handling the playlist
853 To update the playlist, use the C<playlist()> accessor, returning the
854 associated C<Audio::MPD::Playlist> object. You will then be able to call:
856 $mpd->playlist->clear;
858 See C<Audio::MPD::Playlist> documentation for more details on available
859 methods.
863 =head1 BUGS
865 Please report any bugs or feature requests to
866 C<bug-audio-mpd@rt.cpan.org>, or through the web interface at
867 L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Audio-MPD>. I will be
868 notified, and then you'll automatically be notified of progress on your
869 bug as I make changes.
873 =head1 SEE ALSO
875 You can find more information on the mpd project on its homepage at
876 L<http://www.musicpd.org>.wikia.com>.
878 C<Audio::MPD> development takes place on <audio-mpd@googlegroups.com>:
879 feel free to join us. (use L<http://groups.google.com/group/audio-mpd>
880 to sign in). Our git repository is located at
881 L<git://repo.or.cz/audio-mpd.git>, and can be browsed at
882 L<http://repo.or.cz/w/audio-mpd.git>.
885 You can also look for information on this module at:
887 =over 4
889 =item * AnnoCPAN: Annotated CPAN documentation
891 L<http://annocpan.org/dist/Audio-MPD>
893 =item * CPAN Ratings
895 L<http://cpanratings.perl.org/d/Audio-MPD>
897 =item * Open bugs
899 L<http://rt.cpan.org/NoAuth/Bugs.html?Dist=Audio-MPD>
901 =back
905 =head1 AUTHOR
907 Jerome Quelin, C<< <jquelin@cpan.org> >>
909 Original code by Tue Abrahamsen C<< <tue.abrahamsen@gmail.com> >>,
910 documented by Nicholas J. Humfrey C<< <njh@aelius.com> >>.
913 =head1 COPYRIGHT & LICENSE
915 Copyright (c) 2005 Tue Abrahamsen, all rights reserved.
916 Copyright (c) 2006 Nicolas J. Humfrey, all rights reserved.
917 Copyright (c) 2007-2009 Jerome Quelin, all rights reserved.
919 This program is free software; you can redistribute it and/or modify
920 it under the same terms as Perl itself.
922 =cut