use HTML::TreeBuilder to parse hcalendar
[HTML5TV.git] / bin / mplayer.pl
1 #!/usr/bin/perl
2
3 use warnings;
4 use strict;
5
6 use IPC::Open3 qw(open3);
7 use IO::Epoll;
8 use Data::Dump qw(dump);
9 use File::Slurp;
10 use YAML;
11 use JSON;
12 use HTML::TreeBuilder;
13
14
15 my $movie = shift @ARGV
16         || 'www/media/video.ogv';
17 #       || die "usage: $0 path/to/movie.ogv\n";
18
19 my $edl = "/dev/shm/edl";
20 my $subtitles = $movie;
21 $subtitles =~ s{\.\w+$}{.srt};
22
23 my $preroll = 3;
24
25 our $to_mplayer;
26 our $from_mplayer;
27 our $err_mplayer;
28 our $prop = {};
29
30 my $pid = open3( $to_mplayer, $from_mplayer, $err_mplayer,
31          'mplayer',
32                 '-slave', '-idle',
33                 '-quiet',
34                 '-edlout', $edl,
35                 '-osdlevel', 3,
36 );
37
38 my $epfd = epoll_create(10);
39
40 epoll_ctl($epfd, EPOLL_CTL_ADD, fileno STDIN         , EPOLLIN  ) >= 0 || die $!;
41 epoll_ctl($epfd, EPOLL_CTL_ADD, fileno $from_mplayer , EPOLLIN  ) >= 0 || die $!;
42 #epoll_ctl($epfd, EPOLL_CTL_ADD, fileno $to_mplayer   , EPOLLOUT ) >= 0 || die $!;
43
44 sub load_movie {
45         warn "$movie ", -s $movie, " bytes $edl\n";
46         print $to_mplayer qq|loadfile "$movie"\n|;
47         print $to_mplayer "get_property $_\n" foreach ( qw/metadata video_codec video_bitrate width height fps length/ );
48 }
49
50
51 my $term_id = `xdotool getwindowfocus`;
52 our $mplayer_id;
53
54
55 sub focus_mplayer {
56         $mplayer_id ||= `xdotool search mplayer`;
57         warn "focus_mplayer $mplayer_id\n";
58         system "xdotool windowactivate $mplayer_id"
59 }
60
61 sub focus_term {
62         warn "focus_term $term_id\n";
63         system "xdotool windowactivate $term_id";
64 }
65
66 sub preroll {
67         my ( $pos, $osd ) = @_;
68         $osd =~ s{\W+}{ }gs;
69         warn "PREROLL $pos $osd\n";
70         print $to_mplayer "osd_show_text \"PREROLL $osd\" ", $preroll * 1000, "\n";
71         my $to = $pos - $preroll;
72         $to = 0 if $to < 0;
73         print $to_mplayer "set_property time_pos $to\n";
74         print $to_mplayer "get_property time_pos\n";
75         print $to_mplayer "play\n";
76 }
77
78
79 $|=1;
80
81 my $line;
82 my $repl;
83
84 sub repl {
85         print "> ";
86         my $cmd = <STDIN>;
87         warn ">>> $cmd\n";
88         print $to_mplayer $cmd;
89 }
90
91
92 our @subtitles;
93
94 sub html5tv {
95         my $sync;
96
97         my @slide_t;
98
99         my @videos;
100
101         foreach my $s ( @subtitles ) {
102                 push @{ $sync->{htmlEvents}->{'#subtitle'} }, {
103                         startTime => $s->[0],
104                         endTime   => $s->[1],
105                         html      => $s->[2],
106                 };
107
108                 if ( $s->[2] =~ m{video:(.+)} ) {
109                         my $video = $1;
110                         my $path = "www/media/$video";
111                         if ( ! -e $path ) {
112                                 warn "MISSING $path: $!\n";
113                         } else {
114                                 my $frame_dir = "www/media/s/$video";
115                                 system "mplayer -vo jpeg:outdir=$frame_dir -frames 1 -ss 0 www/media/$video"
116                                         if ! -e $frame_dir;
117                                 push @videos, [ @$s, $video ];
118                         }
119                 }
120
121                 next unless $s->[2] =~ m{\[(\d+)\]};
122
123                 my $res = ( $prop->{width} / 4 ) . 'x' . ( $prop->{height} / 4 );
124
125                 push @{ $sync->{customEvents} }, {
126                         startTime => $s->[0],
127                         endTime   => $s->[1],
128                         action    => 'chapterChange',
129                         args => {
130                                 carousel => 'theCarousel',
131                                 id => "chapter$1",
132                                 index => $1,
133                                 title => $s->[2],
134                                 description => $s->[2],
135                                 src => sprintf('media/s/%s/p%03d.jpg', $res, $1),
136                                 href => '',
137                         },
138                 };
139
140                 push @slide_t, $s->[0];
141         }
142
143         my $res = $prop->{width} . 'x' . $prop->{height};
144
145         foreach ( 0 .. $#slide_t ) {
146                 push @{ $sync->{htmlEvents}->{'#slide'} }, {
147                         startTime => $slide_t[$_],
148                         endTime   => $slide_t[$_ + 1] || $prop->{length},
149                         html      => sprintf( '<img src=media/s/%s/p%03d.jpg>', $res, $_ + 1 ),
150                 };
151         }
152
153         my $html5tv = {
154                 sync => $sync,
155                 video => $prop,
156         };
157
158         if ( $prop->{width} && $prop->{height} ) {
159                 foreach my $factor ( 4, 2, 1 ) {
160                         my $w = $prop->{width}  / $factor;
161                         my $h = $prop->{height} / $factor;
162
163                         $html5tv->{slide} = {
164                                 width  => $w,
165                                 height => $h,
166                         } if $factor == 4;
167
168                         my $path = "www/media/s/${w}x${h}";
169                         if ( ! -d $path ) {
170                                 mkdir $path;
171                                 warn "created $path\n";
172                         }
173                 }
174         }
175
176         $html5tv->{video_tags} =
177                 join("\n",
178                         map {
179                                 my $s = $_;
180                                 my $id = $s->[3];
181                                 $id =~ s{\W+}{_}g;
182
183                                 push @{ $html5tv->{sync}->{customEvents} }, {
184                                         startTime => $s->[0],
185                                         endTime   => $s->[1],
186                                         action    => 'additional_video',
187                                         args => {
188                                                 id => $id,
189                                                 title => $s->[2],
190                                                 description => $s->[2],
191                                                 src => "media/s/$s->[3]/00000001.jpg",
192                                                 href => '',
193                                         },
194                                 };
195
196                                 qq|
197                                         <video id="$id" style="display: none" controls="controls" width="$html5tv->{video}->{width}px" height="$html5tv->{video}->{height}px">
198                                         <source src="media/$_->[3]" />
199                                         </video>
200                                 |
201                         } @videos
202                 )
203         ;
204
205         my $nr = 0;
206
207         $html5tv->{subtitles_table}
208                 = qq|<table id="subtitles">|
209                 . join("\n",
210                         map {
211                                 $nr++;
212                                 qq|<tr id="sub_$nr"><td align="right">$_->[0]</td><td align="right">$_->[1]</td><td>$_->[2]</td></tr>|
213                         } @subtitles
214                 )
215                 . qq|</table>|
216                 ;
217
218         my $hcalendar = '<div style="color: red">Create <tt>hcalendar.html</tt> to fill this space</div>';
219         my $hcal_path = 'www/media/hcalendar.html';
220         if ( -e $hcal_path ) {
221                 $html5tv->{hcalendar} = read_file $hcal_path;
222                 my $tree = HTML::TreeBuilder->new;
223                 $tree->parse_file($hcal_path);
224                 if ( my $vevent = $tree->look_down( class => 'vevent' ) ) {
225                         $html5tv->{title} = $vevent->look_down( class=> 'summary' )->as_trimmed_text;
226                 }
227         }
228
229         warn "html5tv ", dump $html5tv;
230
231         my $sync_path = 'www/media/video.js';
232         write_file $sync_path, "var html5tv = " . to_json($html5tv) . " ;\n";
233         warn "sync $sync_path ", -s $sync_path, " bytes\n";
234
235         my $html = read_file 'www/tv.html';
236         $html =~ s|{([^}]+)}|my $n = $1; $n =~ s(\.)(}->{)g; eval "\$html5tv->{$n}"|egs ||
237                 warn "no interpolation in template!";
238
239         write_file 'www/media.html', $html;
240
241         my $carousel_width  = ( $html5tv->{slide}->{width}  + 6 ) * 6; # 6 = left(2)+right(2)+border(2*1)
242         my $carousel_height =   $html5tv->{slide}->{height} + 2;
243
244         write_file 'www/media/video.css', qq|
245
246 .jcarousel-skin-ie7 .jcarousel-container-horizontal,
247 .jcarousel-skin-ie7 .jcarousel-clip-horizontal {
248         width: ${carousel_width}px;
249         height: ${carousel_height}px;
250 }
251
252 .jcarousel-skin-ie7 .jcarousel-item {
253         width: $html5tv->{slide}->{width}px;
254         height: $html5tv->{slide}->{height}px;
255         margin: 0 2px 0 2px;
256 }
257
258 .active {
259         background-color: #ffc;
260 }
261
262 div#videoContainer {
263         width: $html5tv->{video}->{width}px;
264         height: $html5tv->{video}->{height}px;
265         font-family: Arial, Helvetica, sans-serif;
266         margin: 0 10px 0px 0;
267         position: relative;
268         display: inline;
269 }
270
271
272 div#subtitle {
273         bottom: 24px;
274         color: white;
275         font-size: 100%;
276         font-weight: bold;
277         height: 22px;
278         line-height: 1em;
279         margin: 0  0 0 0;
280         padding: 1px 10px 5px 10px ;
281         position: absolute;
282         text-align: center;
283         width: $html5tv->{video}->{width}px;
284 }
285
286
287
288 .jcarousel-skin-ie7 .jcarousel-item img:hover {
289 //      border-color: #555 !important;
290 }
291
292 .jcarousel-skin-ie7 .jcarousel-item:hover div.thumbnailOverlay {
293         visibility: visible !important;
294 }
295
296 .jcarousel-skin-ie7 .jcarousel-item div.thumbnailOverlay {
297         background: black;
298         bottom: 1px;
299         color: #00EEFF;
300         visibility: hidden;
301         font-size: 10px;
302         font-family: Arial, Verdana;
303         font-weight: bold;
304         line-height: 0.9em;
305         opacity: 0.5;
306         position: absolute;
307         text-align: center;
308         z-index: 10;
309         padding: 2px 0 2px 0;
310         width: $html5tv->{slide}->{width}px;
311 }
312
313
314         |;
315
316 }
317
318
319 sub t_srt {
320         my $t = shift;
321         my $hh = int( $t / 3600 );
322         $t -= $hh * 3600;
323         my $mm = int( $t / 60 );
324         $t -= $mm * 60;
325         my $srt = sprintf "%02d:%02d:%04.1f", $hh, $mm, $t;
326         $srt =~ s{\.}{,};
327         return $srt;
328 }
329
330 sub save_subtitles {
331         my $nr = 0;
332         my $srt = "\n";
333         foreach my $s ( @subtitles ) {
334                 $srt .= $nr++ . "\n"
335                         . t_srt( $s->[0] ) . " --> " . t_srt( $s->[1] ) . "\n"
336                         . $s->[2] . "\n\n"
337                         ;
338         }
339         warn $srt;
340
341         write_file $subtitles, $srt;
342         YAML::DumpFile "$subtitles.yaml", sort { $a->[0] <=> $b->[0] } @subtitles;
343
344         print $to_mplayer "sub_remove\n";
345         print $to_mplayer qq|sub_load "$subtitles"\n|;
346         print $to_mplayer "sub_select 1\n";
347
348         html5tv;
349 }
350
351 sub load_subtitles {
352         @subtitles = YAML::LoadFile "$subtitles.yaml";
353         warn "subtitles ", dump @subtitles;
354         save_subtitles;
355 }
356
357 load_subtitles if -e "$subtitles.yaml";
358
359 sub edit_subtitles {
360         print $to_mplayer qq|pause\n|;
361         focus_term;
362         system( qq|vi "$subtitles.yaml"| ) == 0 and load_subtitles;
363         focus_mplayer;
364 }
365
366 sub add_subtitle {
367         print $to_mplayer qq|pause\n|;
368
369         focus_term;
370
371         warn "subtitles ", dump( @subtitles );
372         print "## ";
373         my $line = <STDIN>;
374         $subtitles[ $#subtitles ]->[2] = $line if defined $line;
375
376         save_subtitles;
377
378         focus_mplayer;
379
380         preroll $subtitles[ $#subtitles ]->[0], $line;
381 }
382
383 sub time_pos {
384         print $to_mplayer qq|get_property time_pos\n|;
385         my $pos = <$from_mplayer>;
386         if ( $pos =~ m{^ANS_time_pos=(\d+\.\d+)} ) {
387                 warn "# time_pos $1\n";
388                 return $1;
389         }
390 }
391
392 sub sub_fmt {
393         my $s = shift;
394         sprintf "%1.5f - %1.5f %s %s\n", @$s, join(' | ',@_);
395 }
396
397 sub prev_subtitle {
398         my $pos = time_pos;
399         my $s = ( grep { $_->[0] < $pos } @subtitles )[0];
400         warn "<<<< subtitle ", sub_fmt $s;
401         preroll $s->[0], $s->[2];
402 #       print $to_mplayer "set_property time_pos $s->[0]\n";
403 }
404
405 sub next_subtitle {
406         my $pos = time_pos + $preroll;
407         my $s = ( grep { $_->[0] > $pos } @subtitles )[0];
408         warn ">>>> subtitle ", sub_fmt $s;
409         preroll $s->[0], $s->[2];
410 #       print $to_mplayer "set_property time_pos $s->[0]\n";
411 }
412
413 sub current_subtitle {
414         my $callback = shift;
415         my $pos = time_pos;
416         my $visible;
417         foreach my $nr ( 0 .. $#subtitles ) {
418                 my $s = $subtitles[$nr];
419                 if ( $s->[0] <= $pos && $s->[1] >= $pos ) {
420                         warn sub_fmt $s, $pos;
421                         $visible = $nr;
422                         $callback->( $visible, $pos ) if $callback;
423                         return ( $visible, $pos );
424                 }
425         }
426         warn "# $pos no visible subtitle\n";
427 }
428
429 sub move_subtitle {
430         my $offset = shift;
431         current_subtitle( sub {
432                 my ( $nr, $pos ) = @_;
433                 my $new_start = $subtitles[$nr]->[0] += $offset;
434                 warn "subtitle $nr $pos $offset $new_start\n";
435                 save_subtitles;
436                 preroll $new_start, "$pos $offset $new_start";
437         } );
438 }
439
440
441
442 # XXX main epool loop
443
444 load_movie;
445
446 while ( my $events = epoll_wait($epfd, 10, 1000) ) { # Max 10 events returned, 1s timeout
447
448         warn "no events" unless $events;
449
450         foreach my $e ( @$events ) {
451 #               warn "# event: ", dump($e), $/;
452
453                 my $fileno = $e->[0];
454
455                 if ( $fileno == fileno STDIN ) {
456                         my $chr;
457                         sysread STDIN, $chr, 1;
458                         print $chr;
459                 } elsif ( $fileno == fileno $from_mplayer ) {
460                         my $chr;
461                         sysread $from_mplayer, $chr, 1;
462                         print $chr;
463
464                         if ( $chr =~ m{[\n\r]} ) {
465
466                                 exit if $line =~ m{Exiting};
467
468                                 if ( $line =~ m{ANS_(\w+)=(\S+)} ) {
469                                         $prop->{$1} = $2;
470                                         warn "prop $1 = $2\n";
471                                 } elsif ( $line =~ m{No bind found for key '(.+)'} ) {
472
473                                         # XXX keyboard shortcuts
474
475                                           $1 eq 'c'  ? repl
476                                         : $1 eq ','  ? add_subtitle
477                                         : $1 eq 'F1' ? prev_subtitle
478                                         : $1 eq 'F2' ? move_subtitle( -0.3 )
479                                         : $1 eq 'F3' ? move_subtitle( +0.3 )
480                                         : $1 eq 'F4' ? next_subtitle
481                                         : $1 eq 'F5' ? save_subtitles
482                                         : $1 eq 'F9' ? add_subtitle
483                                         : $1 eq 'F12' ? edit_subtitles
484                                         : warn "CUSTOM $1\n"
485                                         ;
486
487                                 } elsif ( $line =~ m{EDL}i ) {
488
489                                         print $to_mplayer qq|osd_show_text "$line"\n|;
490
491                                         if ( my $pos = time_pos ) {
492                                                 if ( $line =~ m{start}i ) {
493                                                         push @subtitles, [ $pos, $pos, '-' ];
494                                                 } else {
495                                                         $subtitles[ $#subtitles ]->[1] = $pos;
496                                                 }
497                                         }
498                                 }
499
500                                 $line = '';
501                         } else {
502                                 $line .= $chr;
503                         }
504
505
506                 } elsif ( $fileno == fileno $to_mplayer ) {
507 #                       warn "command";
508                 } else {
509                         die "invalid fileno $fileno";
510                 }
511         }
512
513 }
514