v0.19.3
[audio-mpd.git] / lib / Audio / MPD.pm
blob916cc45b99a532b34f009406178b43087eb9facb
2 # This file is part of Audio::MPD
3 # Copyright (c) 2007-2008 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.3';
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 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 Audio::MPD object is created.
596 Note that the module will by default connect to mpd before sending any
597 command, and will disconnect after the command has been issued. This scheme
598 is far from optimal, but allows us not to care about timeout disconnections.
600 B</!\> Note that Audio::MPD is using high-level, blocking sockets. This
601 means that if the mpd server is slow, or hangs for whatever reason, or
602 even crash abruptly, the program will be hung forever in this sub. The
603 POE::Component::Client::MPD module is way safer - you're advised to use
604 it instead of Audio::MPD. Or you can try to set C<conntype> to C<$REUSE>
605 (see Audio::MPD constructor for more details), but you would be then on
606 your own to deal with disconnections.
609 =head1 METHODS
611 =head2 Constructor
613 =over 4
615 =item new( [%opts] )
617 This is the constructor for Audio::MPD. One can specify the following
618 options:
620 =over 4
622 =item hostname => C<$hostname>
624 defaults to environment var MPD_HOST, then to 'localhost'. Note that
625 MPD_HOST can be of the form password@host.
627 =item port => C<$port>
629 defaults to environment var MPD_PORT, then to 6600.
631 =item password => $password
633 defaults to environment var MPD_PASSWORD, then to ''.
635 =item conntype => $type
637 change how the connection to mpd server is handled. It can be either
638 C<$REUSE> to reuse the same connection or C<$ONCE> to open a new
639 connection per command (default)
641 =back
644 =back
647 =head2 Controlling the server
649 =over 4
651 =item $mpd->ping()
653 Sends a ping command to the mpd server.
656 =item $mpd->version()
658 Return mpd's version number as advertised during connection. Note that
659 mpd returns B<protocol> version when connected. This protocol version
660 can differ from the real mpd version. eg, mpd version 0.13.2 is
661 "speaking" and thus advertising version 0.13.0.
665 =item $mpd->kill()
667 Send a message to the MPD server telling it to shut down.
670 =item $mpd->password( [$password] )
672 Change password used to communicate with MPD server to $password.
673 Empty string is assumed if $password is not supplied.
676 =item $mpd->updatedb( [$path] )
678 Force mpd to recan its collection. If $path (relative to MPD's music directory)
679 is supplied, MPD will only scan it - otherwise, MPD will rescan its whole
680 collection.
683 =item $mpd->urlhandlers()
685 Return an array of supported URL schemes.
688 =back
691 =head2 Handling volume & output
693 =over 4
695 =item $mpd->volume( [+][-]$volume )
697 Sets the audio output volume percentage to absolute $volume.
698 If $volume is prefixed by '+' or '-' then the volume is changed relatively
699 by that value.
702 =item $mpd->output_enable( $output )
704 Enable the specified audio output. $output is the ID of the audio output.
707 =item $mpd->output_disable( $output )
709 Disable the specified audio output. $output is the ID of the audio output.
711 =back
714 =head2 Retrieving info from current state
716 =over 4
718 =item $mpd->stats()
720 Return an C<Audio::MPD::Common::Stats> object with the current statistics
721 of MPD. See the associated pod for more information.
724 =item $mpd->status()
726 Return an C<Audio::MPD::Common::Status> object with various information on
727 current MPD server settings. Check the embedded pod for more information on
728 the available accessors.
731 =item $mpd->current()
733 Return an C<Audio::MPD::Common::Item::Song> representing the song currently
734 playing.
737 =item $mpd->song( [$song] )
739 Return an C<Audio::MPD::Common::Item::Song> representing the song number
740 C<$song>. If C<$song> is not supplied, returns the current song.
743 =item $mpd->songid( [$songid] )
745 Return an C<Audio::MPD::Common::Item::Song> representing the song with id
746 C<$songid>. If C<$songid> is not supplied, returns the current song.
748 =back
751 =head2 Altering MPD settings
753 =over 4
755 =item $mpd->repeat( [$repeat] )
757 Set the repeat mode to $repeat (1 or 0). If $repeat is not specified then
758 the repeat mode is toggled.
761 =item $mpd->random( [$random] )
763 Set the random mode to $random (1 or 0). If $random is not specified then
764 the random mode is toggled.
767 =item $mpd->fade( [$seconds] )
769 Enable crossfading and set the duration of crossfade between songs.
770 If $seconds is not specified or $seconds is 0, then crossfading is disabled.
772 =back
775 =head2 Controlling playback
777 =over 4
779 =item $mpd->play( [$song] )
781 Begin playing playlist at song number $song. If no argument supplied,
782 resume playing.
785 =item $mpd->playid( [$songid] )
787 Begin playing playlist at song ID $songid. If no argument supplied,
788 resume playing.
791 =item $mpd->pause( [$state] )
793 Pause playback. If C<$state> is 0 then the current track is unpaused,
794 if $state is 1 then the current track is paused.
796 Note that if C<$state> is not given, pause state will be toggled.
799 =item $mpd->stop()
801 Stop playback.
804 =item $mpd->next()
806 Play next song in playlist.
809 =item $mpd->prev()
811 Play previous song in playlist.
814 =item $mpd->seek( $time, [$song])
816 Seek to $time seconds in song number $song. If $song number is not specified
817 then the perl module will try and seek to $time in the current song.
820 =item $mpd->seekid( $time, $songid )
822 Seek to $time seconds in song ID $songid. If $song number is not specified
823 then the perl module will try and seek to $time in the current song.
825 =back
828 =head2 Searching the collection
830 To search the collection, use the C<collection()> accessor, returning the
831 associated C<Audio::MPD::Collection> object. You will then be able to call:
833 $mpd->collection->random_song();
835 See C<Audio::MPD::Collection> documentation for more details on available
836 methods.
839 =head2 Handling the playlist
841 To update the playlist, use the C<playlist()> accessor, returning the
842 associated C<Audio::MPD::Playlist> object. You will then be able to call:
844 $mpd->playlist->clear;
846 See C<Audio::MPD::Playlist> documentation for more details on available
847 methods.
850 =head1 SEE ALSO
852 You can find more information on the mpd project on its homepage at
853 L<http://www.musicpd.org>, or its wiki L<http://mpd.wikia.com>.
855 Regarding this Perl module, you can report bugs on CPAN via
856 L<http://rt.cpan.org/Public/Bug/Report.html?Queue=Audio-MPD>.
858 Audio::MPD development takes place on <audio-mpd@googlegroups.com>: feel free
859 to join us. (use L<http://groups.google.com/group/audio-mpd> to sign in). Our
860 subversion repository is located at L<https://svn.musicpd.org>.
863 =head1 AUTHOR
865 Jerome Quelin, C<< <jquelin at cpan.org> >>
867 Original code by Tue Abrahamsen C<< <tue.abrahamsen at gmail.com> >>,
868 documented by Nicholas J. Humfrey C<< <njh at aelius.com> >>.
871 =head1 COPYRIGHT & LICENSE
873 Copyright (c) 2005 Tue Abrahamsen, all rights reserved.
874 Copyright (c) 2006 Nicolas J. Humfrey, all rights reserved.
875 Copyright (c) 2007-2008 Jerome Quelin, all rights reserved.
877 This program is free software; you can redistribute it and/or modify
878 it under the same terms as Perl itself.
880 =cut