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