added a note on backward compatibility
[audio-mpd.git] / lib / Audio / MPD.pm
blob817c54fc136eec5f0221866648a110cdfb3c8b7c
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.4';
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 # - hostname => $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.
605 B</!\> Note that C<Audio::MPD> is using high-level, blocking sockets.
606 This means that if the mpd server is slow, or hangs for whatever reason,
607 or even crash abruptly, the program will be hung forever in this sub.
608 The C<POE::Component::Client::MPD> module is way safer - you're advised
609 to use it instead of C<Audio::MPD>. Or you can try to set C<conntype> to
610 C<$REUSE> (see C<Audio::MPD> constructor for more details), but you
611 would be then on your own to deal with disconnections.
614 =head1 METHODS
616 =head2 Constructor
618 =over 4
620 =item new( [%opts] )
622 This is the constructor for C<Audio::MPD>. One can specify the following
623 options:
625 =over 4
627 =item hostname => C<$hostname>
629 defaults to environment var C<MPD_HOST>, then to 'localhost'. Note that
630 C<MPD_HOST> can be of the form password@host.
632 =item port => C<$port>
634 defaults to environment var C<MPD_PORT>, then to 6600.
636 =item password => $password
638 defaults to environment var C<MPD_PASSWORD>, then to ''.
640 =item conntype => $type
642 change how the connection to mpd server is handled. It can be either
643 C<$REUSE> to reuse the same connection or C<$ONCE> to open a new
644 connection per command (default)
646 =back
649 =back
652 =head2 Controlling the server
654 =over 4
656 =item $mpd->ping()
658 Sends a ping command to the mpd server.
661 =item $mpd->version()
663 Return mpd's version number as advertised during connection. Note that
664 mpd returns B<protocol> version when connected. This protocol version
665 can differ from the real mpd version. eg, mpd version 0.13.2 is
666 "speaking" and thus advertising version 0.13.0.
670 =item $mpd->kill()
672 Send a message to the MPD server telling it to shut down.
675 =item $mpd->password( [$password] )
677 Change password used to communicate with MPD server to C<$password>.
678 Empty string is assumed if C<$password> is not supplied.
681 =item $mpd->updatedb( [$path] )
683 Force mpd to recan its collection. If C<$path> (relative to MPD's music
684 directory) is supplied, MPD will only scan it - otherwise, MPD will
685 rescan its whole collection.
688 =item $mpd->urlhandlers()
690 Return an array of supported URL schemes.
693 =back
696 =head2 Handling volume & output
698 =over 4
700 =item $mpd->volume( [+][-]$volume )
702 Sets the audio output volume percentage to absolute C<$volume>. If
703 C<$volume> is prefixed by '+' or '-' then the volume is changed
704 relatively by that value.
707 =item $mpd->output_enable( $output )
709 Enable the specified audio output. C<$output> is the ID of the audio
710 output.
713 =item $mpd->output_disable( $output )
715 Disable the specified audio output. C<$output> is the ID of the audio
716 output.
718 =back
721 =head2 Retrieving info from current state
723 =over 4
725 =item $mpd->stats()
727 Return an C<Audio::MPD::Common::Stats> object with the current statistics
728 of MPD. See the associated pod for more information.
731 =item $mpd->status()
733 Return an C<Audio::MPD::Common::Status> object with various information on
734 current MPD server settings. Check the embedded pod for more information on
735 the available accessors.
738 =item $mpd->current()
740 Return an C<Audio::MPD::Common::Item::Song> representing the song currently
741 playing.
744 =item $mpd->song( [$song] )
746 Return an C<Audio::MPD::Common::Item::Song> representing the song number
747 C<$song>. If C<$song> is not supplied, returns the current song.
750 =item $mpd->songid( [$songid] )
752 Return an C<Audio::MPD::Common::Item::Song> representing the song with id
753 C<$songid>. If C<$songid> is not supplied, returns the current song.
755 =back
758 =head2 Altering MPD settings
760 =over 4
762 =item $mpd->repeat( [$repeat] )
764 Set the repeat mode to C<$repeat> (1 or 0). If C<$repeat> is not
765 specified then the repeat mode is toggled.
768 =item $mpd->random( [$random] )
770 Set the random mode to C<$random> (1 or 0). If C<$random> is not
771 specified then the random mode is toggled.
774 =item $mpd->fade( [$seconds] )
776 Enable crossfading and set the duration of crossfade between songs. If
777 C<$seconds> is not specified or $seconds is 0, then crossfading is
778 disabled.
780 =back
783 =head2 Controlling playback
785 =over 4
787 =item $mpd->play( [$song] )
789 Begin playing playlist at song number C<$song>. If no argument supplied,
790 resume playing.
793 =item $mpd->playid( [$songid] )
795 Begin playing playlist at song ID C<$songid>. If no argument supplied,
796 resume playing.
799 =item $mpd->pause( [$state] )
801 Pause playback. If C<$state> is 0 then the current track is unpaused,
802 if C<$state> is 1 then the current track is paused.
804 Note that if C<$state> is not given, pause state will be toggled.
807 =item $mpd->stop()
809 Stop playback.
812 =item $mpd->next()
814 Play next song in playlist.
817 =item $mpd->prev()
819 Play previous song in playlist.
822 =item $mpd->seek( $time, [$song])
824 Seek to C<$time> seconds in song number C<$song>. If C<$song> number is
825 not specified then the perl module will try and seek to C<$time> in the
826 current song.
829 =item $mpd->seekid( $time, $songid )
831 Seek to C<$time> seconds in song ID C<$songid>. If C<$song> number is
832 not specified then the perl module will try and seek to C<$time> in the
833 current song.
835 =back
838 =head2 Searching the collection
840 To search the collection, use the C<collection()> accessor, returning the
841 associated C<Audio::MPD::Collection> object. You will then be able to call:
843 $mpd->collection->random_song;
845 See C<Audio::MPD::Collection> documentation for more details on available
846 methods.
849 =head2 Handling the playlist
851 To update the playlist, use the C<playlist()> accessor, returning the
852 associated C<Audio::MPD::Playlist> object. You will then be able to call:
854 $mpd->playlist->clear;
856 See C<Audio::MPD::Playlist> documentation for more details on available
857 methods.
861 =head1 BUGS
863 Please report any bugs or feature requests to
864 C<bug-audio-mpd@rt.cpan.org>, or through the web interface at
865 L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Audio-MPD>. I will be
866 notified, and then you'll automatically be notified of progress on your
867 bug as I make changes.
871 =head1 SEE ALSO
873 You can find more information on the mpd project on its homepage at
874 L<http://www.musicpd.org>.wikia.com>.
876 C<Audio::MPD> development takes place on <audio-mpd@googlegroups.com>:
877 feel free to join us. (use L<http://groups.google.com/group/audio-mpd>
878 to sign in). Our git repository is located at
879 L<git://repo.or.cz/audio-mpd.git>, and can be browsed at
880 L<http://repo.or.cz/w/audio-mpd.git>.
883 You can also look for information on this module at:
885 =over 4
887 =item * AnnoCPAN: Annotated CPAN documentation
889 L<http://annocpan.org/dist/Audio-MPD>
891 =item * CPAN Ratings
893 L<http://cpanratings.perl.org/d/Audio-MPD>
895 =item * Open bugs
897 L<http://rt.cpan.org/NoAuth/Bugs.html?Dist=Audio-MPD>
899 =back
903 =head1 AUTHOR
905 Jerome Quelin, C<< <jquelin@cpan.org> >>
907 Original code by Tue Abrahamsen C<< <tue.abrahamsen@gmail.com> >>,
908 documented by Nicholas J. Humfrey C<< <njh@aelius.com> >>.
911 =head1 COPYRIGHT & LICENSE
913 Copyright (c) 2005 Tue Abrahamsen, all rights reserved.
914 Copyright (c) 2006 Nicolas J. Humfrey, all rights reserved.
915 Copyright (c) 2007-2009 Jerome Quelin, all rights reserved.
917 This program is free software; you can redistribute it and/or modify
918 it under the same terms as Perl itself.
920 =cut