ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/AnyEvent-MPV/MPV.pm
(Generate patch)

Comparing AnyEvent-MPV/MPV.pm (file contents):
Revision 1.4 by root, Sun Mar 19 20:56:59 2023 UTC vs.
Revision 1.19 by root, Sun Mar 26 17:15:18 2023 UTC

4 4
5=head1 SYNOPSIS 5=head1 SYNOPSIS
6 6
7 use AnyEvent::MPV; 7 use AnyEvent::MPV;
8 8
9 my $videofile = "path/to/file.mkv";
10 use AnyEvent;
11 my $mpv = AnyEvent::MPV->new (trace => 1);
12 $mpv->start ("--idle=yes");
13 $mpv->cmd (loadfile => $mpv->escape_binary ($videofile));
14 my $quit = AE::cv;
15 $mpv->register_event (end_file => $quit);
16 $quit->recv;
17
18
9=head1 DESCRIPTION 19=head1 DESCRIPTION
10 20
21This module allows you to remote control F<mpv> (a video player). It also
11This module is an L<AnyEvent> user, you need to make sure that you use and 22is an L<AnyEvent> user, you need to make sure that you use and run a
12run a supported event loop. 23supported event loop.
24
25There are other modules doing this, and I haven't looked much at them
26other than to decide that they don't handle encodings correctly, and since
27none of them use AnyEvent, I wrote my own. When in doubt, have a look at
28them, too.
29
30Knowledge of the L<mpv command
31interface|https://mpv.io/manual/stable/#command-interface> is required to
32use this module.
33
34Features of this module are:
35
36=over
37
38=item uses AnyEvent, so integrates well into most event-based programs
39
40=item supports asynchronous and synchronous operation
41
42=item allows you to properly pass binary filenames
43
44=item accepts data encoded in any way (does not crash when mpv replies with non UTF-8 data)
45
46=item features a simple keybind/event system
47
48=back
49
50=head2 OVERVIEW OF OPERATION
51
52This module forks an F<mpv> process and uses F<--input-ipc-client> (or
53equivalent) to create a bidirectional communication channel between it and
54the F<mpv> process.
55
56It then speaks the somewhat JSON-looking (but not really being JSON)
57protocol that F<mpv> implements to both send it commands, decode and
58handle replies, and handle asynchronous events.
59
60Here is a very simple client:
61
62 use AnyEvent;
63 use AnyEvent::MPV;
64
65 my $videofile = "./xyzzy.mkv";
66
67 my $mpv = AnyEvent::MPV->new (trace => 1);
68
69 $mpv->start ("--", $videofile);
70
71 my $timer = AE::timer 2, 0, my $quit = AE::cv;
72 $quit->recv;
73
74This starts F<mpv> with the two arguments C<--> and C<$videofile>, which
75it should load and play. It then waits two seconds by starting a timer and
76quits. The C<trace> argument to the constructor makes F<mpv> more verbose
77and also prints the commands and responses, so you can have an idea what
78is going on.
79
80In my case, the above example would output something like this:
81
82 [uosc] Disabled because original osc is enabled!
83 mpv> {"event":"start-file","playlist_entry_id":1}
84 mpv> {"event":"tracks-changed"}
85 (+) Video --vid=1 (*) (h264 480x480 30.000fps)
86 mpv> {"event":"metadata-update"}
87 mpv> {"event":"file-loaded"}
88 Using hardware decoding (nvdec).
89 mpv> {"event":"video-reconfig"}
90 VO: [gpu] 480x480 cuda[nv12]
91 mpv> {"event":"video-reconfig"}
92 mpv> {"event":"playback-restart"}
93
94This is not usually very useful (you could just run F<mpv> as a simple
95shell command), so let us load the file at runtime:
96
97 use AnyEvent;
98 use AnyEvent::MPV;
99
100 my $videofile = "./xyzzy.mkv";
101
102 my $mpv = AnyEvent::MPV->new (
103 trace => 1,
104 args => ["--pause", "--idle=yes"],
105 );
106
107 $mpv->start;
108 $mpv->cmd_recv (loadfile => $mpv->escape_binary ($videofile));
109 $mpv->cmd ("set", "pause", "no");
110
111 my $timer = AE::timer 2, 0, my $quit = AE::cv;
112 $quit->recv;
113
114This specifies extra arguments in the constructor - these arguments are
115used every time you C<< ->start >> F<mpv>, while the arguments to C<<
116->start >> are only used for this specific clal to0 C<start>. The argument
117F<--pause> keeps F<mpv> in pause mode (i.e. it does not play the file
118after loading it), and C<--idle=yes> tells F<mpv> to not quit when it does
119not have a playlist - as no files are specified on the command line.
120
121To load a file, we then send it a C<loadfile> command, which accepts, as
122first argument, the URL or path to a video file. To make sure F<mpv> does
123not misinterpret the path as a URL, it was prefixed with F<./> (similarly
124to "protecting" paths in perls C<open>).
125
126Since commands send I<to> F<mpv> are send in UTF-8, we need to escape the
127filename (which might be in any encoding) using the C<esscape_binary>
128method - this is not needed if your filenames are just ascii, or magically
129get interpreted correctly, but if you accept arbitrary filenamews (e.g.
130from the user), you need to do this.
131
132The C<cmd_recv> method then queues the command, waits for a reply and
133returns the reply data (or croaks on error). F<mpv> would, at this point,
134load the file and, if everything was successful, show the first frame and
135pause. Note that, since F<mpv> is implement rather synchronously itself,
136do not expect commands to fail in many circumstances - for example, fit
137he file does not exit, you will likely get an event, but the C<loadfile>
138command itself will run successfully.
139
140To unpause, we send another command, C<set>, to set the C<pause> property
141to C<no>, this time using the C<cmd> method, which queues the command, but
142instead of waiting for a reply, it immediately returns a condvar that cna
143be used to receive results.
144
145This should then cause F<mpv> to start playing the video.
146
147It then again waits two seconds and quits.
148
149Now, just waiting two seconds is rather, eh, unuseful, so let's look at
150receiving events (using a somewhat embellished example):
151
152 use AnyEvent;
153 use AnyEvent::MPV;
154
155 my $videofile = "xyzzy.mkv";
156
157 my $quit = AE::cv;
158
159 my $mpv = AnyEvent::MPV->new (
160 trace => 1,
161 args => ["--pause", "--idle=yes"],
162 );
163
164 $mpv->start;
165
166 $mpv->register_event (start_file => sub {
167 $mpv->cmd ("set", "pause", "no");
168 });
169
170 $mpv->register_event (end_file => sub {
171 my ($mpv, $event, $data) = @_;
172
173 print "end-file<$data->{reason}>\n";
174 $quit->send;
175 });
176
177 $mpv->cmd (loadfile => $mpv->escape_binary ($videofile));
178
179 $quit->recv;
180
181This example uses a global condvar C<$quit> to wait for the file to finish
182playing. Also, most of the logic is now implement in event handlers.
183
184The two events handlers we register are C<start-file>, which is emitted by
185F<mpv> once it has loaded a new file, and C<end-file>, which signals the
186end of a file (underscores are internally replaced by minus signs, so you
187cna speicfy event names with either).
188
189In the C<start-file> event, we again set the C<pause> property to C<no>
190so the movie starts playing. For the C<end-file> event, we tell the main
191program to quit by invoking C<$quit>.
192
193This should conclude the basics of operation. There are a few more
194examples later in the documentation.
195
196=head2 ENCODING CONVENTIONS
197
198As a rule of thumb, all data you pass to this module to be sent to F<mpv>
199is expected to be in unicode. To pass something that isn't, you need to
200escape it using C<escape_binary>.
201
202Data received from F<mpv>, however, is I<not> decoded to unicode, as data
203returned by F<mpv> is not generally encoded in unicode, and the encoding
204is usually unspecified. So if you receive data and expect it to be in
205unicode, you need to first decode it from UTF-8, but note that this might
206fail. This is not a limitation of this module - F<mpv> simply does not
207specify nor guarantee a specific encoding, or any encoding at all, in its
208protocol.
209
210=head2 METHODS
211
212=over
13 213
14=cut 214=cut
15 215
16package AnyEvent::MPV; 216package AnyEvent::MPV;
17 217
21use Scalar::Util (); 221use Scalar::Util ();
22 222
23use AnyEvent (); 223use AnyEvent ();
24use AnyEvent::Util (); 224use AnyEvent::Util ();
25 225
226our $VERSION = '1.01';
227
228sub OBSID() { 0x10000000000000 } # 2**52
229
26our $JSON = eval { require JSON::XS; JSON::XS:: } 230our $JSON = eval { require JSON::XS; JSON::XS:: }
27 || do { require JSON::PP; JSON::PP:: }; 231 || do { require JSON::PP; JSON::PP:: };
28 232
29our $VERSION = '0.1'; 233our $JSON_ENCODER = $JSON->new->utf8;
234our $JSON_DECODER = $JSON->new->latin1;
30 235
31our $mpv_path; # last mpv path used 236our $mpv_path; # last mpv path used
32our $mpv_optionlist; # output of mpv --list-options 237our $mpv_optionlist; # output of mpv --list-options
238
239=item $mpv = AnyEvent::MPV->new (key => value...)
240
241Creates a new C<mpv> object, but does not yet do anything. The support key-value pairs are:
242
243=over
244
245=item mpv => $path
246
247The path to the F<mpv> binary to use - by default, C<mpv> is used and
248therefore, uses your C<PATH> to find it.
249
250=item args => [...]
251
252Arguments to pass to F<mpv>. These arguments are passed after the
253hardcoded arguments used by this module, but before the arguments passed
254ot C<start>. It does not matter whether you specify your arguments using
255this key, or in the C<start> call, but when you invoke F<mpv> multiple
256times, typically the arguments used for all invocations go here, while
257arguments used for specific invocations (e..g filenames) are passed to
258C<start>.
259
260=item trace => false|true|coderef
261
262Enables tracing if true. In trace mode, output from F<mpv> is printed to
263standard error using a C<< mpv> >> prefix, and commands sent to F<mpv>
264are printed with a C<< >mpv >> prefix.
265
266If a code reference is passed, then instead of printing to standard
267errort, this coderef is invoked with a first arfgument being either
268C<< mpv> >> or C<< >mpv >>, and the second argument being a string to
269display. The default implementation simply does this:
270
271 sub {
272 warn "$_[0] $_[1]\n";
273 }
274
275=item on_eof => $coderef->($mpv)
276
277=item on_event => $coderef->($mpv, $event, $data)
278
279=item on_key => $coderef->($mpv, $string)
280
281These are invoked by the default method implementation of the same name -
282see below.
283
284=back
285
286=cut
33 287
34sub new { 288sub new {
35 my ($class, %kv) = @_; 289 my ($class, %kv) = @_;
36 290
37 bless { 291 bless {
38 mpv => "mpv", 292 mpv => "mpv",
39 args => [], 293 args => [],
40 %kv, 294 %kv,
41 }, $class 295 }, $class
42} 296}
297
298=item $string = $mpv->escape_binary ($string)
299
300This module excects all command data sent to F<mpv> to be in unicode. Some
301things are not, such as filenames. To pass binary data such as filenames
302through a comamnd, you need to escape it using this method.
303
304The simplest example is a C<loadfile> command:
305
306 $mpv->cmd_recv (loadfile => $mpv->escape_binary ($path));
307
308=cut
43 309
44# can be used to escape filenames 310# can be used to escape filenames
45sub escape_binary { 311sub escape_binary {
46 shift; 312 shift;
47 local $_ = shift; 313 local $_ = shift;
48 # we escape every "illegal" octet using U+10e5df HEX. this is later undone in cmd 314 # we escape every "illegal" octet using U+10e5df HEX. this is later undone in cmd
49 s/([\x00-\x1f\x80-\xff])/sprintf "\x{10e5df}%02x", ord $1/ge; 315 s/([\x00-\x1f\x80-\xff])/sprintf "\x{10e5df}%02x", ord $1/ge;
50 $_ 316 $_
51} 317}
52 318
319=item $started = $mpv->start (argument...)
320
321Starts F<mpv>, passing the given arguemnts as extra arguments to
322F<mpv>. If F<mpv> is already running, it returns false, otherwise it
323returns a true value, so you can easily start F<mpv> on demand by calling
324C<start> just before using it, and if it is already running, it will not
325be started again.
326
327The arguments passwd to F<mpv> are a set of hardcoded built-in arguments,
328followed by the arguments specified in the constructor, followed by the
329arguments passwd to this method. The built-in arguments currently are
330F<--no-input-terminal>, F<--really-quiet> (or F<--quiet> in C<trace>
331mode), and C<--input-ipc-client> (or equivalent).
332
333Some commonly used and/or even useful arguments you might want to pass are:
334
335=over
336
337=item F<--idle=yes> or F<--idle=once> to keep F<mpv> from quitting when you
338don't specify a file to play.
339
340=item F<--pause>, to keep F<mpv> from instantly starting to play a file, in case you want to
341inspect/change properties first.
342
343=item F<--force-window=no> (or similar), to keep F<mpv> from instantly opening a window, or to force it to do so.
344
345=item F<--audio-client-name=yourappname>, to make sure audio streams are associated witht eh right program.
346
347=item F<--wid=id>, to embed F<mpv> into another application.
348
349=item F<--no-terminal>, F<--no-input-default-bindings>, F<--no-input-cursor>, F<--input-conf=/dev/null>, F<--input-vo-keyboard=no> - to ensure only you control input.
350
351=back
352
353The return value can be used to decide whether F<mpv> needs initializing:
354
355 if ($mpv->start) {
356 $mpv->bind_key (...);
357 $mpv->cmd (set => property => value);
358 ...
359 }
360
361You can immediately starting sending commands when this method returns,
362even if F<mpv> has not yet started.
363
364=cut
365
53sub start { 366sub start {
54 my ($self, @extra_args) = @_; 367 my ($self, @extra_args) = @_;
55 368
56 return 0 if $self->{fh}; 369 return 0 if $self->{fh};
57 370
73 fcntl $slave, Fcntl::F_SETFD, 0; 386 fcntl $slave, Fcntl::F_SETFD, 0;
74 387
75 my $input_file = $options =~ /\s--input-ipc-client\s/ ? "input-ipc-client" : "input-file"; 388 my $input_file = $options =~ /\s--input-ipc-client\s/ ? "input-ipc-client" : "input-file";
76 389
77 exec $self->{mpv}, 390 exec $self->{mpv},
78 qw(--no-input-terminal --idle=yes --pause), 391 qw(--no-input-terminal),
79 ($self->{trace} ? "--quiet" : "--really-quiet"), 392 ($self->{trace} ? "--quiet" : "--really-quiet"),
80 "--$input_file=fd://" . (fileno $slave), 393 "--$input_file=fd://" . (fileno $slave),
81 @{ $self->{args} }, 394 @{ $self->{args} },
82 @extra_args; 395 @extra_args;
83 exit 1; 396 exit 1;
84 } 397 }
85 398
86 $self->{fh} = $fh; 399 $self->{fh} = $fh;
87 400
88 my $trace = delete $self->{trace} || sub { }; 401 my $trace = $self->{trace} || sub { };
89 402
90 $trace = sub { warn "$_[0] $_[1]\n" } if $trace && !ref $trace; 403 $trace = sub { warn "$_[0] $_[1]\n" } if $trace && !ref $trace;
91 404
92 my $buf; 405 my $buf;
93 my $wbuf;
94 406
95 Scalar::Util::weaken $self; 407 Scalar::Util::weaken $self;
96 408
97 $self->{rw} = AE::io $fh, 0, sub { 409 $self->{rw} = AE::io $fh, 0, sub {
98 if (sysread $fh, $buf, 8192, length $buf) { 410 if (sysread $fh, $buf, 8192, length $buf) {
99 while ($buf =~ s/^([^\n]+)\n//) { 411 while ($buf =~ s/^([^\n]+)\n//) {
100 $trace->("mpv>" => "$1"); 412 $trace->("mpv>" => "$1");
101 413
102 if ("{" eq substr $1, 0, 1) { 414 if ("{" eq substr $1, 0, 1) {
103 eval { 415 eval {
104 my $reply = JSON::XS->new->latin1->decode ($1); 416 my $reply = $JSON_DECODER->decode ($1);
105 417
106 if (exists $reply->{event}) { 418 if (defined (my $event = delete $reply->{event})) {
107 if ( 419 if (
108 $reply->{event} eq "client-message" 420 $event eq "client-message"
109 and $reply->{args}[0] eq "AnyEvent::MPV" 421 and $reply->{args}[0] eq "AnyEvent::MPV"
110 ) { 422 ) {
111 if ($reply->{args}[1] eq "key") { 423 if ($reply->{args}[1] eq "key") {
112 (my $key = $reply->{args}[2]) =~ s/\\x(..)/chr hex $1/ge; 424 (my $key = $reply->{args}[2]) =~ s/\\x(..)/chr hex $1/ge;
113 $self->on_key ($key); 425 $self->on_key ($key);
114 } 426 }
427 } elsif (
428 $event eq "property-change"
429 and OBSID <= $reply->{id}
430 ) {
431 if (my $cb = $self->{obscb}{$reply->{id}}) {
432 $cb->($self, $event, $reply->{data});
433 }
115 } else { 434 } else {
435 if (my $cbs = $self->{evtcb}{$event}) {
436 for my $evtid (keys %$cbs) {
437 my $cb = $cbs->{$evtid}
438 or next;
439 $cb->($self, $event, $reply);
440 }
441 }
442
116 $self->on_event ($reply); 443 $self->on_event ($event, $reply);
117 } 444 }
118 } elsif (exists $reply->{request_id}) { 445 } elsif (exists $reply->{request_id}) {
119 my $cv = delete $self->{cmd_cv}{$reply->{request_id}}; 446 my $cv = delete $self->{cmdcv}{$reply->{request_id}};
120 447
121 unless ($cv) { 448 unless ($cv) {
122 warn "no cv found for request id <$reply->{request_id}>\n"; 449 warn "no cv found for request id <$reply->{request_id}>\n";
123 next; 450 next;
124 } 451 }
144 $self->stop; 471 $self->stop;
145 $self->on_eof; 472 $self->on_eof;
146 } 473 }
147 }; 474 };
148 475
476 my $wbuf;
477 my $reqid;
478
149 $self->{_send} = sub { 479 $self->{_cmd} = sub {
150 $wbuf .= "$_[0]\n"; 480 my $cv = AE::cv;
151 481
482 $self->{cmdcv}{++$reqid} = $cv;
483
484 my $cmd = $JSON_ENCODER->encode ({ command => ref $_[0] ? $_[0] : \@_, request_id => $reqid*1 });
485
486 # (un-)apply escape_binary hack
487 $cmd =~ s/\xf4\x8e\x97\x9f(..)/sprintf sprintf "\\x%02x", hex $1/ges; # f48e979f == 10e5df in utf-8
488
152 $trace->(">mpv" => "$_[0]"); 489 $trace->(">mpv" => $cmd);
490
491 $wbuf .= "$cmd\n";
153 492
154 $self->{ww} ||= AE::io $fh, 1, sub { 493 $self->{ww} ||= AE::io $fh, 1, sub {
155 my $len = syswrite $fh, $wbuf; 494 my $len = syswrite $fh, $wbuf;
156 substr $wbuf, 0, $len, ""; 495 substr $wbuf, 0, $len, "";
157 undef $self->{ww} unless length $wbuf; 496 undef $self->{ww} unless length $wbuf;
158 }; 497 };
498
499 $cv
159 }; 500 };
160 501
161 1 502 1
162} 503}
504
505sub DESTROY {
506 $_[0]->stop;
507}
508
509=item $mpv->stop
510
511Ensures that F<mpv> is being stopped, by killing F<mpv> with a C<TERM>
512signal if needed. After this, you can C<< ->start >> a new instance again.
513
514=cut
515
516sub stop {
517 my ($self) = @_;
518
519 delete $self->{rw};
520 delete $self->{ww};
521
522 if ($self->{pid}) {
523
524 close delete $self->{fh}; # current mpv versions should cleanup on their own on close
525
526 kill TERM => $self->{pid};
527
528 }
529
530 delete $self->{pid};
531 delete $self->{cmdcv};
532 delete $self->{evtid};
533 delete $self->{evtcb};
534 delete $self->{obsid};
535 delete $self->{obscb};
536 delete $self->{wbuf};
537}
538
539=item $mpv->on_eof
540
541This method is called when F<mpv> quits - usually unexpectedly. The
542default implementation will call the C<on_eof> code reference specified in
543the constructor, or do nothing if none was given.
544
545For subclassing, see I<SUBCLASSING>, below.
546
547=cut
163 548
164sub on_eof { 549sub on_eof {
165 my ($self) = @_; 550 my ($self) = @_;
166 551
167 $self->{on_eof}($self) if $self->{on_eof}; 552 $self->{on_eof}($self) if $self->{on_eof};
168} 553}
169 554
555=item $mpv->on_event ($event, $data)
556
557This method is called when F<mpv> sends an asynchronous event. The default
558implementation will call the C<on_event> code reference specified in the
559constructor, or do nothing if none was given.
560
561The first/implicit argument is the C<$mpv> object, the second is the
562event name (same as C<< $data->{event} >>, purely for convenience), and
563the third argument is the event object as sent by F<mpv> (sans C<event>
564key). See L<List of events|https://mpv.io/manual/stable/#list-of-events>
565in its documentation.
566
567For subclassing, see I<SUBCLASSING>, below.
568
569=cut
570
170sub on_event { 571sub on_event {
171 my ($self, $key) = @_; 572 my ($self, $event, $data) = @_;
172 573
173 $self->{on_event}($self, $key) if $self->{on_event}; 574 $self->{on_event}($self, $event, $data) if $self->{on_event};
174} 575}
576
577=item $mpv->on_key ($string)
578
579Invoked when a key declared by C<< ->bind_key >> is pressed. The default
580invokes the C<on_key> code reference specified in the constructor with the
581C<$mpv> object and the key name as arguments, or do nothing if none was
582given.
583
584For more details and examples, see the C<bind_key> method.
585
586For subclassing, see I<SUBCLASSING>, below.
587
588=cut
175 589
176sub on_key { 590sub on_key {
177 my ($self, $key) = @_; 591 my ($self, $key) = @_;
178 592
179 $self->{on_key}($self, $key) if $self->{on_key}; 593 $self->{on_key}($self, $key) if $self->{on_key};
180} 594}
181 595
596=item $mpv->cmd ($command => $arg, $arg...)
597
598Queues a command to be sent to F<mpv>, using the given arguments, and
599immediately return a condvar.
600
601See L<the mpv
602documentation|https://mpv.io/manual/stable/#list-of-input-commands> for
603details on individual commands.
604
605The condvar can be ignored:
606
607 $mpv->cmd (set_property => "deinterlace", "yes");
608
609Or it can be used to synchronously wait for the command results:
610
611 $cv = $mpv->cmd (get_property => "video-format");
612 $format = $cv->recv;
613
614 # or simpler:
615
616 $format = $mpv->cmd (get_property => "video-format")->recv;
617
618 # or even simpler:
619
620 $format = $mpv->cmd_recv (get_property => "video-format");
621
622Or you can set a callback:
623
624 $cv = $mpv->cmd (get_property => "video-format");
625 $cv->cb (sub {
626 my $format = $_[0]->recv;
627 });
628
629On error, the condvar will croak when C<recv> is called.
630
631=cut
632
182sub cmd { 633sub cmd {
183 my ($self, @cmd) = @_; 634 my $self = shift;
184 635
185 my $cv = AE::cv; 636 $self->{_cmd}->(@_)
186
187 my $reqid = ++$self->{reqid};
188 $self->{cmd_cv}{$reqid} = $cv;
189
190 my $cmd = JSON::XS::encode_json { command => ref $cmd[0] ? $cmd[0] : \@cmd, request_id => $reqid*1 };
191
192 # (un-)apply escape_binary hack
193 $cmd =~ s/\xf4\x8e\x97\x9f(..)/sprintf sprintf "\\x%02x", hex $1/ges; # f48e979f == 10e5df in utf-8
194
195 $self->{_send}($cmd);
196
197 $cv
198} 637}
638
639=item $result = $mpv->cmd_recv ($command => $arg, $arg...)
640
641The same as calling C<cmd> and immediately C<recv> on its return
642value. Useful when you don't want to mess with F<mpv> asynchronously or
643simply needs to have the result:
644
645 $mpv->cmd_recv ("stop");
646 $position = $mpv->cmd_recv ("get_property", "playback-time");
647
648=cut
199 649
200sub cmd_recv { 650sub cmd_recv {
201 &cmd->recv 651 &cmd->recv
202} 652}
203 653
654=item $mpv->bind_key ($INPUT => $string)
655
656This is an extension implement by this module to make it easy to get key
657events. The way this is implemented is to bind a C<client-message> witha
658first argument of C<AnyEvent::MPV> and the C<$string> you passed. This
659C<$string> is then passed to the C<on_key> handle when the key is
660proessed, e.g.:
661
662 my $mpv = AnyEvent::MPV->new (
663 on_key => sub {
664 my ($mpv, $key) = @_;
665
666 if ($key eq "letmeout") {
667 print "user pressed escape\n";
668 }
669 },
670 );
671
672 $mpv_>bind_key (ESC => "letmeout");
673
674You cna find a list of key names L<in the mpv
675documentation|https://mpv.io/manual/stable/#key-names>.
676
677The key configuration is lost when F<mpv> is stopped and must be (re-)done
678after every C<start>.
679
680=cut
681
204sub bind_key { 682sub bind_key {
205 my ($self, $key, $event) = @_; 683 my ($self, $key, $event) = @_;
206 684
207 $event =~ s/([^A-Za-z0-9\-_])/sprintf "\\x%02x", ord $1/ge; 685 $event =~ s/([^A-Za-z0-9\-_])/sprintf "\\x%02x", ord $1/ge;
208 $self->cmd (keybind => $key => "no-osd script-message AnyEvent::MPV key $event"); 686 $self->cmd (keybind => $key => "no-osd script-message AnyEvent::MPV key $event");
209} 687}
210 688
211sub stop { 689=item [$guard] = $mpv->register_event ($event => $coderef->($mpv, $event, $data))
690
691This method registers a callback to be invoked for a specific
692event. Whenever the event occurs, it calls the coderef with the C<$mpv>
693object, the C<$event> name and the event object, just like the C<on_event>
694method.
695
696For a lst of events, see L<the mpv
697documentation|https://mpv.io/manual/stable/#list-of-events>. Any
698underscore in the event name is replaced by a minus sign, so you can
699specify event names using underscores for easier quoting in Perl.
700
701In void context, the handler stays registered until C<stop> is called. In
702any other context, it returns a guard object that, when destroyed, will
703unregister the handler.
704
705You can register multiple handlers for the same event, and this method
706does not interfere with the C<on_event> mechanism. That is, you can
707completely ignore this method and handle events in a C<on_event> handler,
708or mix both approaches as you see fit.
709
710Note that unlike commands, event handlers are registered immediately, that
711is, you can issue a command, then register an event handler and then get
712an event for this handler I<before> the command is even sent to F<mpv>. If
713this kind of race is an issue, you can issue a dummy command such as
714C<get_version> and register the handler when the reply is received.
715
716=cut
717
718sub AnyEvent::MPV::Unevent::DESTROY {
719 my ($evtcb, $event, $evtid) = @{$_[0]};
720 delete $evtcb->{$event}{$evtid};
721}
722
723sub register_event {
724 my ($self, $event, $cb) = @_;
725
726 $event =~ y/_/-/;
727
728 my $evtid = ++$self->{evtid};
729 $self->{evtcb}{$event}{$evtid} = $cb;
730
731 defined wantarray
732 and bless [$self->{evtcb}, $event, $evtid], AnyEvent::MPV::Unevent::
733}
734
735=item [$guard] = $mpv->observe_property ($name => $coderef->($mpv, $name, $value))
736
737=item [$guard] = $mpv->observe_property_string ($name => $coderef->($mpv, $name, $value))
738
739These methods wrap a registry system around F<mpv>'s C<observe_property>
740and C<observe_property_string> commands - every time the named property
741changes, the coderef is invoked with the C<$mpv> object, the name of the
742property and the new value.
743
744For a list of properties that you can observe, see L<the mpv
745documentation|https://mpv.io/manual/stable/#property-list>.
746
747Due to the (sane :) way F<mpv> handles these requests, you will always
748get a property cxhange event right after registering an observer (meaning
749you don't have to query the current value), and it is also possible to
750register multiple observers for the same property - they will all be
751handled properly.
752
753When called in void context, the observer stays in place until F<mpv>
754is stopped. In any otrher context, these methods return a guard
755object that, when it goes out of scope, unregisters the observe using
756C<unobserve_property>.
757
758Internally, this method uses observer ids of 2**52 (0x10000000000000) or
759higher - it will not interfere with lower ovserver ids, so it is possible
760to completely ignore this system and execute C<observe_property> commands
761yourself, whilst listening to C<property-change> events - as long as your
762ids stay below 2**52.
763
764Example: register observers for changtes in C<aid> and C<sid>. Note that
765a dummy statement is added to make sure the method is called in void
766context.
767
768 sub register_observers {
212 my ($self) = @_; 769 my ($mpv) = @_;
213 770
214 if ($self->{pid}) { 771 $mpv->observe_property (aid => sub {
215 delete $self->{rw}; 772 my ($mpv, $name, $value) = @_;
216 delete $self->{ww}; 773 print "property aid (=$name) has changed to $value\n";
774 });
217 775
218 close delete $self->{fh}; # current mpv versions should cleanup on their own on close 776 $mpv->observe_property (sid => sub {
777 my ($mpv, $name, $value) = @_;
778 print "property sid (=$name) has changed to $value\n";
779 });
219 780
220 kill TERM => $self->{pid}; 781 () # ensure the above method is called in void context
221
222 delete $self->{pid};
223 } 782 }
783
784=cut
785
786sub AnyEvent::MPV::Unobserve::DESTROY {
787 my ($mpv, $obscb, $obsid) = @{$_[0]};
788
789 delete $obscb->{$obsid};
790
791 if ($obscb == $mpv->{obscb}) {
792 $mpv->cmd (unobserve_property => $obsid+0);
793 }
224} 794}
795
796sub _observe_property {
797 my ($self, $type, $property, $cb) = @_;
798
799 my $obsid = OBSID + ++$self->{obsid};
800 $self->cmd ($type => $obsid+0, $property);
801 $self->{obscb}{$obsid} = $cb;
802
803 defined wantarray and do {
804 my $unobserve = bless [$self, $self->{obscb}, $obsid], AnyEvent::MPV::Unobserve::;
805 Scalar::Util::weaken $unobserve->[0];
806 $unobserve
807 }
808}
809
810sub observe_property {
811 my ($self, $property, $cb) = @_;
812
813 $self->_observe_property (observe_property => $property, $cb)
814}
815
816sub observe_property_string {
817 my ($self, $property, $cb) = @_;
818
819 $self->_observe_property (observe_property_string => $property, $cb)
820}
821
822=back
823
824=head2 SUBCLASSING
825
826Like most perl objects, C<AnyEvent::MPV> objects are implemented as
827hashes, with the constructor simply storing all passed key-value pairs in
828the object. If you want to subclass to provide your own C<on_*> methods,
829be my guest and rummage around in the internals as much as you wish - the
830only guarantee that this module dcoes is that it will not use keys with
831double colons in the name, so youc an use those, or chose to simply not
832care and deal with the breakage.
833
834If you don't want to go to the effort of subclassing this module, you can
835also specify all event handlers as constructor keys.
836
837=head1 EXAMPLES
838
839Here are some real-world code snippets, thrown in here mainly to give you
840some example code to copy.
841
842=head2 doomfrontend
843
844At one point I replaced mythtv-frontend by my own terminal-based video
845player (based on rxvt-unicode). I toyed with the diea of using F<mpv>'s
846subtitle engine to create the user interface, but that is hard to use
847since you don't know how big your letters are. It is also where most of
848this modules code has originally been developed in.
849
850It uses a unified input queue to handle various remote controls, so its
851event handling needs are very simple - it simply feeds all events into the
852input queue:
853
854 my $mpv = AnyEvent::MPV->new (
855 mpv => $MPV,
856 args => \@MPV_ARGS,
857 on_event => sub {
858 input_feed "mpv/$_[1]", $_[2];
859 },
860 on_key => sub {
861 input_feed $_[1];
862 },
863 on_eof => sub {
864 input_feed "mpv/quit";
865 },
866 );
867
868 ...
869
870 $mpv->start ("--idle=yes", "--pause", "--force-window=no");
871
872It also doesn't use complicated command line arguments - the file search
873options have the most impact, as they prevent F<mpv> from scanning
874directories with tens of thousands of files for subtitles and more:
875
876 --audio-client-name=doomfrontend
877 --osd-on-seek=msg-bar --osd-bar-align-y=-0.85 --osd-bar-w=95
878 --sub-auto=exact --audio-file-auto=exact
879
880Since it runs on a TV without a desktop environemnt, it tries to keep complications such as dbus
881away and the screensaver happy:
882
883 # prevent xscreensaver from doing something stupid, such as starting dbus
884 $ENV{DBUS_SESSION_BUS_ADDRESS} = "/"; # prevent dbus autostart for sure
885 $ENV{XDG_CURRENT_DESKTOP} = "generic";
886
887It does bind a number of keys to internal (to doomfrontend) commands:
888
889 for (
890 List::Util::pairs qw(
891 ESC return
892 q return
893 ENTER enter
894 SPACE pause
895 [ steprev
896 ] stepfwd
897 j subtitle
898 BS red
899 i green
900 o yellow
901 b blue
902 D triangle
903 UP up
904 DOWN down
905 RIGHT right
906 LEFT left
907 ),
908 (map { ("KP$_" => "num$_") } 0..9),
909 KP_INS => 0, # KP0, but different
910 ) {
911 $mpv->bind_key ($_->[0] => $_->[1]);
912 }
913
914It also reacts to sponsorblock chapters, so it needs to know when vidoe
915chapters change. Preadting C<AnyEvent::MPV>, it handles observers
916manually:
917
918 $mpv->cmd (observe_property => 1, "chapter-metadata");
919
920It also tries to apply an F<mpv> profile, if it exists:
921
922 eval {
923 # the profile is optional
924 $mpv->cmd ("apply-profile" => "doomfrontend");
925 };
926
927Most of the complicated parts deal with saving and restoring per-video
928data, such as bookmarks, playing position, selected audio and subtitle
929tracks and so on. However, since it uses L<Coro>, it can conveniently
930block and wait for replies, which is n ot possible in purely event based
931programs, as you are not allowed to block inside event callbacks in most
932event loops. This simplifies the code quite a bit.
933
934When the file to be played is a Tv recording done by mythtv, it uses the
935C<appending> protocol and deinterlacing:
936
937 if (is_myth $mpv_path) {
938 $mpv_path = "appending://$mpv_path";
939 $initial_deinterlace = 1;
940 }
941
942Otherwise, it sets some defaults and loads the file (I forgot what the
943C<dummy> argument is for, but I am sure it is needed by some F<mpv>
944version):
945
946 $mpv->cmd ("script-message", "osc-visibility", "never", "dummy");
947 $mpv->cmd ("set", "vid", "auto");
948 $mpv->cmd ("set", "aid", "auto");
949 $mpv->cmd ("set", "sid", "no");
950 $mpv->cmd ("set", "file-local-options/chapters-file", $mpv->escape_binary ("$mpv_path.chapters"));
951 $mpv->cmd ("loadfile", $mpv->escape_binary ($mpv_path));
952 $mpv->cmd ("script-message", "osc-visibility", "auto", "dummy");
953
954Handling events makes the main bulk of video playback code. For example,
955various ways of ending playback:
956
957 if ($INPUT eq "mpv/quit") { # should not happen, but allows user to kill etc. without consequence
958 $status = 1;
959 mpv_init; # try reinit
960 last;
961
962 } elsif ($INPUT eq "mpv/idle") { # normal end-of-file
963 last;
964
965 } elsif ($INPUT eq "return") {
966 $status = 1;
967 last;
968
969Or the code that actually starts playback, once the file is loaded:
970
971 our %SAVE_PROPERTY = (aid => 1, sid => 1, "audio-delay" => 1);
972
973 ...
974
975 my $oid = 100;
976
977 } elsif ($INPUT eq "mpv/file-loaded") { # start playing, configure video
978 $mpv->cmd ("seek", $playback_start, "absolute+exact") if $playback_start > 0;
979
980 my $target_fps = eval { $mpv->cmd_recv ("get_property", "container-fps") } || 60;
981 $target_fps *= play_video_speed_mult;
982 set_fps $target_fps;
983
984 unless (eval { $mpv->cmd_recv ("get_property", "video-format") }) {
985 $mpv->cmd ("set", "file-local-options/lavfi-complex", "[aid1] asplit [ao], showcqt=..., format=yuv420p [vo]");
986 };
987
988 for my $prop (keys %SAVE_PROPERTY) {
989 if (exists $PLAYING_STATE->{"mpv_$prop"}) {
990 $mpv->cmd ("set", "$prop", $PLAYING_STATE->{"mpv_$prop"} . "");
991 }
992
993 $mpv->cmd ("observe_property", ++$oid, $prop);
994 }
995
996 play_video_set_speed;
997 $mpv->cmd ("set", "osd-level", "$OSD_LEVEL");
998 $mpv->cmd ("observe_property", ++$oid, "osd-level");
999 $mpv->cmd ("set", "pause", "no");
1000
1001 $mpv->cmd ("set_property", "deinterlace", "yes")
1002 if $initial_deinterlace;
1003
1004There is a lot going on here. First it seeks to the actual playback
1005position, if it is not at the start of the file (it would probaby be more
1006efficient to set the starting position before loading the file, though,
1007but this is good enough).
1008
1009Then it plays with the display fps, to set it to something harmonious
1010w.r.t. the video framerate.
1011
1012If the file does not have a video part, it assumes it is an audio file and
1013sets a visualizer.
1014
1015Also, a number of properties are not global, but per-file. At the moment,
1016this is C<audio-delay>, and the current audio/subtitle track, which it
1017sets, and also creates an observer. Again, this doesn'T use the observe
1018functionality of this module, but handles it itself, assigning obsevrer
1019ids 100+ to temporary/per-file observers.
1020
1021Lastly, it sets some global (or per-youtube-uploader) parameters, such as
1022speed, and unpauses. Property changes are handled like other input events:
1023
1024 } elsif ($INPUT eq "mpv/property-change") {
1025 my $prop = $INPUT_DATA->{name};
1026
1027 if ($prop eq "chapter-metadata") {
1028 if ($INPUT_DATA->{data}{TITLE} =~ /^\[SponsorBlock\]: (.*)/) {
1029 my $section = $1;
1030 my $skip;
1031
1032 $skip ||= $SPONSOR_SKIP{$_}
1033 for split /\s*,\s*/, $section;
1034
1035 if (defined $skip) {
1036 if ($skip) {
1037 # delay a bit, in case we get two metadata changes in quick succession, e.g.
1038 # because we have a skip at file load time.
1039 $skip_delay = AE::timer 2/50, 0, sub {
1040 $mpv->cmd ("no-osd", "add", "chapter", 1);
1041 $mpv->cmd ("show-text", "skipped sponsorblock section \"$section\"", 3000);
1042 };
1043 } else {
1044 undef $skip_delay;
1045 $mpv->cmd ("show-text", "NOT skipping sponsorblock section \"$section\"", 3000);
1046 }
1047 } else {
1048 $mpv->cmd ("show-text", "UNRECOGNIZED sponsorblock section \"$section\"", 60000);
1049 }
1050 } else {
1051 # cancel a queued skip
1052 undef $skip_delay;
1053 }
1054
1055 } elsif (exists $SAVE_PROPERTY{$prop}) {
1056 $PLAYING_STATE->{"mpv_$prop"} = $INPUT_DATA->{data};
1057 ::state_save;
1058 }
1059
1060This saves back the per-file properties, and also handles chapter changes
1061in a hacky way.
1062
1063Most of the handlers are very simple, though. For example:
1064
1065 } elsif ($INPUT eq "pause") {
1066 $mpv->cmd ("cycle", "pause");
1067 $PLAYING_STATE->{curpos} = $mpv->cmd_recv ("get_property", "playback-time");
1068 } elsif ($INPUT eq "right") {
1069 $mpv->cmd ("osd-msg-bar", "seek", 30, "relative+exact");
1070 } elsif ($INPUT eq "left") {
1071 $mpv->cmd ("osd-msg-bar", "seek", -5, "relative+exact");
1072 } elsif ($INPUT eq "up") {
1073 $mpv->cmd ("osd-msg-bar", "seek", +600, "relative+exact");
1074 } elsif ($INPUT eq "down") {
1075 $mpv->cmd ("osd-msg-bar", "seek", -600, "relative+exact");
1076 } elsif ($INPUT eq "select") {
1077 $mpv->cmd ("osd-msg-bar", "add", "audio-delay", "-0.100");
1078 } elsif ($INPUT eq "start") {
1079 $mpv->cmd ("osd-msg-bar", "add", "audio-delay", "0.100");
1080 } elsif ($INPUT eq "intfwd") {
1081 $mpv->cmd ("no-osd", "frame-step");
1082 } elsif ($INPUT eq "audio") {
1083 $mpv->cmd ("osd-auto", "cycle", "audio");
1084 } elsif ($INPUT eq "subtitle") {
1085 $mpv->cmd ("osd-auto", "cycle", "sub");
1086 } elsif ($INPUT eq "triangle") {
1087 $mpv->cmd ("osd-auto", "cycle", "deinterlace");
1088
1089Once a file has finished playing (or the user strops playback), it pauses,
1090unobserves the per-file observers, and saves the current position for to
1091be able to resume:
1092
1093 $mpv->cmd ("set", "pause", "yes");
1094
1095 while ($oid > 100) {
1096 $mpv->cmd ("unobserve_property", $oid--);
1097 }
1098
1099 $PLAYING_STATE->{curpos} = $mpv->cmd_recv ("get_property", "playback-time");
1100
1101And thats most of the F<mpv>-related code.
1102
1103=head2 F<Gtk2::CV>
1104
1105F<Gtk2::CV> is low-feature image viewer that I use many times daily
1106because it can handle directories with millions of files without falling
1107over. It also had the ability to play videos for ages, but it used an
1108older, crappier protocol to talk to F<mpv> and used F<ffprobe> before
1109playing each file instead of letting F<mpv> handle format/size detection.
1110
1111After writing this module, I decided to upgprade Gtk2::CV by making use
1112of it, with the goal of getting rid of F<ffprobe> and being ablew to
1113reuse F<mpv> processes, which would have a multitude of speed benefits
1114(for example, fork+exec of F<mpv> caused the kernel to close all file
1115descriptors, which could take minutes if a large file was being copied via
1116NFS, as the kernel waited for thr buffers to be flushed on close - not
1117having to start F<mpv> gets rid of this issue).
1118
1119Setting up is only complicated by the fact that F<mpv> needs to be
1120embedded into an existing window. To keep control of all inputs,
1121F<Gtk2::CV> puts an eventbox in front of F<mpv>, so F<mpv> receives no
1122input events:
1123
1124 $self->{mpv} = AnyEvent::MPV->new (
1125 trace => $ENV{CV_MPV_TRACE},
1126 );
1127
1128 # create an eventbox, so we receive all input events
1129 my $box = $self->{mpv_eventbox} = new Gtk2::EventBox;
1130 $box->set_above_child (1);
1131 $box->set_visible_window (0);
1132 $box->set_events ([]);
1133 $box->can_focus (0);
1134
1135 # create a drawingarea that mpv can display into
1136 my $window = $self->{mpv_window} = new Gtk2::DrawingArea;
1137 $box->add ($window);
1138
1139 # put the drawingarea intot he eventbox, and the eventbox into our display window
1140 $self->add ($box);
1141
1142 # we need to pass the window id to F<mpv>, which means we need to realise
1143 # the drawingarea, so an X window is allocated for it.
1144 $self->show_all;
1145 $window->realize;
1146 my $xid = $window->window->get_xid;
1147
1148Then it starts F<mpv> using this setup:
1149
1150 local $ENV{LC_ALL} = "POSIX";
1151 $self->{mpv}->start (
1152 "--no-terminal",
1153 "--no-input-terminal",
1154 "--no-input-default-bindings",
1155 "--no-input-cursor",
1156 "--input-conf=/dev/null",
1157 "--input-vo-keyboard=no",
1158
1159 "--loop-file=inf",
1160 "--force-window=yes",
1161 "--idle=yes",
1162
1163 "--audio-client-name=CV",
1164
1165 "--osc=yes", # --osc=no displays fading play/pause buttons instead
1166
1167 "--wid=$xid",
1168 );
1169
1170 $self->{mpv}->cmd ("script-message" => "osc-visibility" => "never", "dummy");
1171 $self->{mpv}->cmd ("osc-idlescreen" => "no");
1172
1173It also prepares a hack to force a ConfigureNotify event on every vidoe
1174reconfig:
1175
1176 # force a configurenotify on every video-reconfig
1177 $self->{mpv_reconfig} = $self->{mpv}->register_event (video_reconfig => sub {
1178 my ($mpv, $event, $data) = @_;
1179
1180 $self->mpv_window_update;
1181 });
1182
1183The way this is done is by doing a "dummy" resize to 1x1 and back:
1184
1185 $self->{mpv_window}->window->resize (1, 1),
1186 $self->{mpv_window}->window->resize ($self->{w}, $self->{h});
1187
1188Without this, F<mpv> often doesn't "get" the correct window size. Doing
1189it this way is not nice, but I didn't fine a nicer way to do it.
1190
1191When no file is being played, F<mpv> is hidden and prepared:
1192
1193 $self->{mpv_eventbox}->hide;
1194
1195 $self->{mpv}->cmd (set_property => "pause" => "yes");
1196 $self->{mpv}->cmd ("playlist_remove", "current");
1197 $self->{mpv}->cmd (set_property => "video-rotate" => 0);
1198 $self->{mpv}->cmd (set_property => "lavfi-complex" => "");
1199
1200Loading a file is a bit more complicated, as bluray and DVD rips are
1201supported:
1202
1203 if ($moviedir) {
1204 if ($moviedir eq "br") {
1205 $mpv->cmd (set => "bluray-device" => $path);
1206 $mpv->cmd (loadfile => "bd://");
1207 } elsif ($moviedir eq "dvd") {
1208 $mpv->cmd (set => "dvd-device" => $path);
1209 $mpv->cmd (loadfile => "dvd://");
1210 }
1211 } elsif ($type eq "video/iso-bluray") {
1212 $mpv->cmd (set => "bluray-device" => $path);
1213 $mpv->cmd (loadfile => "bd://");
1214 } else {
1215 $mpv->cmd (loadfile => $mpv->escape_binary ($path));
1216 }
1217
1218After this, C<Gtk2::CV> waits for the file to be loaded, video to be
1219configured, and then queries the video size (to resize its own window)
1220and video format (to decide whether an audio visualizer is needed for
1221audio playback). The problematic word here is "wait", as this needs to be
1222imploemented using callbacks.
1223
1224This made the code much harder to write, as the whole setup is very
1225asynchronous (C<Gtk2::CV> talks to the command interface in F<mpv>, which
1226talks to the decode and playback parts, all of which run asynchronously
1227w.r.t. each other. In practise, this can mean that C<Gtk2::CV> waits for
1228a file to be loaded by F<mpv> while the command interface of F<mpv> still
1229deals with the previous file and the decoder still handles an even older
1230file). Adding to this fact is that Gtk2::CV is bound by the glib event
1231loop, which means we cannot wait for replies form F<mpv> anywhere, so
1232everything has to be chained callbacks.
1233
1234The way this is handled is by creating a new empty hash ref that is unique
1235for each loaded file, and use it to detect whether the event is old or
1236not, and also store C<AnyEvent::MPV> guard objects in it:
1237
1238 # every time we loaded a file, we create a new hash
1239 my $guards = $self->{mpv_guards} = { };
1240
1241Then, when we wait for an event to occur, delete the handler, and, if the
1242C<mpv_guards> object has changed, we ignore it. Something like this:
1243
1244 $guards->{file_loaded} = $mpv->register_event (file_loaded => sub {
1245 delete $guards->{file_loaded};
1246 return if $guards != $self->{mpv_guards};
1247
1248Commands do not have guards since they cnanot be cancelled, so we don't
1249have to do this for commands. But what prevents us form misinterpreting
1250an old event? Since F<mpv> (by default) handles commands synchronously,
1251we can queue a dummy command, whose only purpose is to tell us when all
1252previous commands are done. We use C<get_version> for this.
1253
1254The simplified code looks like this:
1255
1256 Scalar::Util::weaken $self;
1257
1258 $mpv->cmd ("get_version")->cb (sub {
1259
1260 $guards->{file_loaded} = $mpv->register_event (file_loaded => sub {
1261 delete $guards->{file_loaded};
1262 return if $guards != $self->{mpv_guards};
1263
1264 $mpv->cmd (get_property => "video-format")->cb (sub {
1265 return if $guards != $self->{mpv_guards};
1266
1267 # video-format handling
1268 return if eval { $_[0]->recv; 1 };
1269
1270 # no video? assume audio and visualize, cpu usage be damned
1271 $mpv->cmd (set => "lavfi-complex" => ...");
1272 });
1273
1274 $guards->{show} = $mpv->register_event (video_reconfig => sub {
1275 delete $guards->{show};
1276 return if $guards != $self->{mpv_guards};
1277
1278 $self->{mpv_eventbox}->show_all;
1279
1280 $w = $mpv->cmd (get_property => "dwidth");
1281 $h = $mpv->cmd (get_property => "dheight");
1282
1283 $h->cb (sub {
1284 $w = eval { $w->recv };
1285 $h = eval { $h->recv };
1286
1287 $mpv->cmd (set_property => "pause" => "no");
1288
1289 if ($w && $h) {
1290 # resize our window
1291 }
1292
1293 });
1294 });
1295
1296 });
1297
1298 });
1299
1300Most of the rest of the code is much simpler and just deals with forwarding user commands:
1301
1302 } elsif ($key == $Gtk2::Gdk::Keysyms{Right}) { $mpv->cmd ("osd-msg-bar" => seek => "+10");
1303 } elsif ($key == $Gtk2::Gdk::Keysyms{Left} ) { $mpv->cmd ("osd-msg-bar" => seek => "-10");
1304 } elsif ($key == $Gtk2::Gdk::Keysyms{Up} ) { $mpv->cmd ("osd-msg-bar" => seek => "+60");
1305 } elsif ($key == $Gtk2::Gdk::Keysyms{Down} ) { $mpv->cmd ("osd-msg-bar" => seek => "-60");
1306 } elsif ($key == $Gtk2::Gdk::Keysyms{a}) ) { $mpv->cmd ("osd-msg-msg" => cycle => "audio");
1307 } elsif ($key == $Gtk2::Gdk::Keysyms{j} ) { $mpv->cmd ("osd-msg-msg" => cycle => "sub");
1308 } elsif ($key == $Gtk2::Gdk::Keysyms{o} ) { $mpv->cmd ("no-osd" => "cycle-values", "osd-level", "2", "3", "0", "2");
1309 } elsif ($key == $Gtk2::Gdk::Keysyms{p} ) { $mpv->cmd ("no-osd" => cycle => "pause");
1310 } elsif ($key == $Gtk2::Gdk::Keysyms{9} ) { $mpv->cmd ("osd-msg-bar" => add => "ao-volume", "-2");
1311 } elsif ($key == $Gtk2::Gdk::Keysyms{0} ) { $mpv->cmd ("osd-msg-bar" => add => "ao-volume", "+2");
225 1312
226=head1 SEE ALSO 1313=head1 SEE ALSO
227 1314
228L<AnyEvent>. 1315L<AnyEvent>, L<the mpv command documentation|https://mpv.io/manual/stable/#command-interface>.
229 1316
230=head1 AUTHOR 1317=head1 AUTHOR
231 1318
232 Marc Lehmann <schmorp@schmorp.de> 1319 Marc Lehmann <schmorp@schmorp.de>
233 http://home.schmorp.de/ 1320 http://home.schmorp.de/

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines