don't create html5tv without slides defined
[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         foreach my $factor ( 4, 2, 1 ) {
169                 my $w = $prop->{width}  / $factor;
170                 my $h = $prop->{height} / $factor;
171
172                 my $path = "www/media/s/${w}x${h}";
173
174                 if ( ! -d $path ) {
175                         mkdir $path;
176                         warn "created $path\n";
177
178                         foreach my $hires ( glob 'www/media/s/hires/p*.jpg' ) {
179
180                                 my $file = $hires;
181                                 $file =~ s{^.+/(p\d+\.\w)}{$path/$1};
182
183                                 my $im = Imager->new( file => $hires );
184                                 $im->scale( xpixels => $w, ypixels => $h, type => 'min' )->write( file => $file );
185                                 warn "resized $file ", -s $file, " bytes\n";
186                         }
187                 }
188
189                 if ( $factor == $slide_factor ) {
190                         my $im = Imager->new( file => "$path/p001.jpg" );
191                         $slide_width  = $im->getwidth;
192                         $slide_height = $im->getheight;
193                 }
194
195         }
196
197         my $html5tv = {
198                 sync => $sync,
199                 video => $prop,
200                 slide => {
201                         width => $slide_width,
202                         height => $slide_height,
203                 },
204         };
205
206         $html5tv->{video_tags} =
207                 join("\n",
208                         map {
209                                 my $s = $_;
210                                 my $id = $s->[3];
211                                 $id =~ s{\W+}{_}g;
212
213                                 push @{ $html5tv->{sync}->{customEvents} }, {
214                                         startTime => $s->[0],
215                                         endTime   => $s->[1],
216                                         action    => 'additional_video',
217                                         args => {
218                                                 id => $id,
219                                                 title => $s->[2],
220                                                 description => $s->[2],
221                                                 src => "media/s/$s->[3]/00000001.jpg",
222                                                 href => '',
223                                         },
224                                 };
225
226                                 qq|
227                                         <video id="$id" style="display: none" controls="controls" width="$html5tv->{video}->{width}px" height="$html5tv->{video}->{height}px">
228                                         <source src="media/$_->[3]" />
229                                         </video>
230                                 |
231                         } @videos
232                 )
233         ;
234
235         my $index = 1;
236
237         sub customEvents_sorted {
238                 sort { $a->{startTime} <=> $b->{startTime} }
239                 @{ $html5tv->{sync}->{customEvents} }
240         }
241                 
242
243         foreach my $e (
244                 sort { $a->{startTime} <=> $b->{startTime} }
245                 @{ $html5tv->{sync}->{customEvents} }
246         ) {
247                 $e->{args}->{index} = $index++;
248                 warn "e = ", dump $e;
249         }
250
251         warn "last customEvent $index\n";
252
253         $html5tv->{subtitles_table}
254                 = qq|<table id="subtitles">|
255                 . join("\n",
256                         map { qq|
257                                 <tr id="sub_$_->{index}">
258                                         <td class="seek_video">$_->{startTime}</td>
259                                         <td class="seek_video">$_->{endTime}</td>
260                                         <td>$_->{args}->{title}</td>
261                                 </tr>
262                         | }
263                         customEvents_sorted
264                 )
265                 . qq|</table><a href="media/video.srt">download subtitles</a>|
266                 ;
267
268         my $hcalendar = '<div style="color: red">Create <tt>hcalendar.html</tt> to fill this space</div>';
269         my $hcal_path = 'www/media/hcalendar.html';
270         if ( -e $hcal_path ) {
271                 $html5tv->{hcalendar} = read_file $hcal_path;
272                 my $tree = HTML::TreeBuilder->new;
273                 $tree->parse_file($hcal_path);
274                 if ( my $vevent = $tree->look_down( class => 'vevent' ) ) {
275                         $html5tv->{title} = $vevent->look_down( class=> 'summary' )->as_trimmed_text;
276                 }
277         }
278
279         warn "html5tv ", dump $html5tv;
280
281         my $sync_path = 'www/media/video.js';
282         write_file $sync_path, "var html5tv = " . to_json($html5tv) . " ;\n";
283         warn "sync $sync_path ", -s $sync_path, " bytes\n";
284
285         my $html = read_file 'www/tv.html';
286         $html =~ s|{([^}]+)}|my $n = $1; $n =~ s(\.)(}->{)g; eval "\$html5tv->{$n}"|egs ||
287                 warn "no interpolation in template!";
288
289         write_file 'www/media.html', $html;
290
291         my $carousel_width = $prop->{width} + Imager->new( file => "www/media/s/$res/p001.jpg" )->getwidth - 80;
292         $carousel_width -= $carousel_width % ( $slide_width + 6 ); # round to full slide
293         my $carousel_height =   $slide_height + 2;
294
295         write_file 'www/media/video.css', qq|
296
297 .jcarousel-skin-ie7 .jcarousel-container-horizontal,
298 .jcarousel-skin-ie7 .jcarousel-clip-horizontal {
299         width: ${carousel_width}px;
300         height: ${carousel_height}px;
301 }
302
303 .jcarousel-skin-ie7 .jcarousel-item {
304         width: ${slide_width}px;
305         height: ${slide_height}px;
306         margin: 0 2px 0 2px;
307 }
308
309 .active {
310         background-color: #ffc;
311 }
312
313 div#videoContainer {
314         width: $prop->{width}px;
315         height: $prop->{height}px;
316         font-family: Arial, Helvetica, sans-serif;
317         margin: 0 10px 0px 0;
318         position: relative;
319         display: inline;
320 }
321
322
323 div#subtitle {
324         bottom: 24px;
325         color: white;
326         font-size: 100%;
327         font-weight: bold;
328         height: 22px;
329         line-height: 1em;
330         margin: 0  0 0 0;
331         padding: 1px 10px 5px 10px ;
332         position: absolute;
333         text-align: center;
334         width: $html5tv->{video}->{width}px;
335 }
336
337
338
339 .jcarousel-skin-ie7 .jcarousel-item img:hover {
340 //      border-color: #555 !important;
341 }
342
343 .jcarousel-skin-ie7 .jcarousel-item:hover div.thumbnailOverlay {
344         visibility: visible !important;
345 }
346
347 .jcarousel-skin-ie7 .jcarousel-item div.thumbnailOverlay {
348         background: black;
349         bottom: 1px;
350         color: #00EEFF;
351         visibility: hidden;
352         font-size: 10px;
353         font-family: Arial, Verdana;
354         font-weight: bold;
355         line-height: 0.9em;
356         opacity: 0.5;
357         position: absolute;
358         text-align: center;
359         z-index: 10;
360         padding: 2px 0 2px 0;
361         width: ${slide_width}px;
362 }
363
364 .seek_video {
365         text-align: right;
366         font-family: monospace;
367 }
368
369         |;
370
371         return 1;
372 }
373
374
375 sub t_srt {
376         my $t = shift;
377         my $hh = int( $t / 3600 );
378         $t -= $hh * 3600;
379         my $mm = int( $t / 60 );
380         $t -= $mm * 60;
381         my $srt = sprintf "%02d:%02d:%04.1f", $hh, $mm, $t;
382         $srt =~ s{\.}{,};
383         return $srt;
384 }
385
386 sub save_subtitles {
387
388         html5tv || return;
389
390         my $nr = 0;
391         my $srt = "\n";
392         foreach my $s ( @subtitles ) {
393                 $srt .= $nr++ . "\n"
394                         . t_srt( $s->[0] ) . " --> " . t_srt( $s->[1] ) . "\n"
395                         . $s->[2] . "\n\n"
396                         ;
397         }
398         warn $srt;
399
400         write_file $subtitles, $srt;
401         YAML::DumpFile "$subtitles.yaml", sort { $a->[0] <=> $b->[0] } @subtitles;
402
403         print $to_mplayer "sub_remove\n";
404         print $to_mplayer qq|sub_load "$subtitles"\n|;
405         print $to_mplayer "sub_select 1\n";
406 }
407
408 sub load_subtitles {
409         @subtitles = YAML::LoadFile "$subtitles.yaml";
410         warn "subtitles ", dump @subtitles;
411         save_subtitles;
412 }
413
414 load_subtitles if -e "$subtitles.yaml";
415
416 sub edit_subtitles {
417         print $to_mplayer qq|pause\n|;
418         focus_term;
419         system( qq|vi "$subtitles.yaml"| ) == 0 and load_subtitles;
420         focus_mplayer;
421 }
422
423 sub add_subtitle {
424         print $to_mplayer qq|pause\n|;
425
426         focus_term;
427
428         warn "subtitles ", dump( @subtitles );
429         print "## ";
430         my $line = <STDIN>;
431         $subtitles[ $#subtitles ]->[2] = $line if defined $line;
432
433         save_subtitles;
434
435         focus_mplayer;
436
437         preroll $subtitles[ $#subtitles ]->[0], $line;
438 }
439
440 sub time_pos {
441         print $to_mplayer qq|get_property time_pos\n|;
442         my $pos = <$from_mplayer>;
443         if ( $pos =~ m{^ANS_time_pos=(\d+\.\d+)} ) {
444                 warn "# time_pos $1\n";
445                 return $1;
446         }
447 }
448
449 sub sub_fmt {
450         my $s = shift;
451         sprintf "%1.5f - %1.5f %s %s\n", @$s, join(' | ',@_);
452 }
453
454 sub prev_subtitle {
455         my $pos = time_pos;
456         my $s = ( grep { $_->[0] < $pos } @subtitles )[0];
457         warn "<<<< subtitle ", sub_fmt $s;
458         preroll $s->[0], $s->[2];
459 #       print $to_mplayer "set_property time_pos $s->[0]\n";
460 }
461
462 sub next_subtitle {
463         my $pos = time_pos + $preroll;
464         my $s = ( grep { $_->[0] > $pos } @subtitles )[0];
465         warn ">>>> subtitle ", sub_fmt $s;
466         preroll $s->[0], $s->[2];
467 #       print $to_mplayer "set_property time_pos $s->[0]\n";
468 }
469
470 sub current_subtitle {
471         my $callback = shift;
472         my $pos = time_pos;
473         my $visible;
474         foreach my $nr ( 0 .. $#subtitles ) {
475                 my $s = $subtitles[$nr];
476                 if ( $s->[0] <= $pos && $s->[1] >= $pos ) {
477                         warn sub_fmt $s, $pos;
478                         $visible = $nr;
479                         $callback->( $visible, $pos ) if $callback;
480                         return ( $visible, $pos );
481                 }
482         }
483         warn "# $pos no visible subtitle\n";
484 }
485
486 sub move_subtitle {
487         my $offset = shift;
488         current_subtitle( sub {
489                 my ( $nr, $pos ) = @_;
490                 my $new_start = $subtitles[$nr]->[0] += $offset;
491                 warn "subtitle $nr $pos $offset $new_start\n";
492                 save_subtitles;
493                 preroll $new_start, "$pos $offset $new_start";
494         } );
495 }
496
497
498
499 # XXX main epool loop
500
501 load_movie;
502
503 while ( my $events = epoll_wait($epfd, 10, 1000) ) { # Max 10 events returned, 1s timeout
504
505         warn "no events" unless $events;
506
507         foreach my $e ( @$events ) {
508 #               warn "# event: ", dump($e), $/;
509
510                 my $fileno = $e->[0];
511
512                 if ( $fileno == fileno STDIN ) {
513                         my $chr;
514                         sysread STDIN, $chr, 1;
515                         print $chr;
516                 } elsif ( $fileno == fileno $from_mplayer ) {
517                         my $chr;
518                         sysread $from_mplayer, $chr, 1;
519                         print $chr;
520
521                         if ( $chr =~ m{[\n\r]} ) {
522
523                                 exit if $line =~ m{Exiting};
524
525                                 if ( $line =~ m{ANS_(\w+)=(\S+)} ) {
526                                         $prop->{$1} = $2;
527                                         warn "prop $1 = $2\n";
528                                 } elsif ( $line =~ m{No bind found for key '(.+)'} ) {
529
530                                         # XXX keyboard shortcuts
531
532                                           $1 eq 'c'  ? repl
533                                         : $1 eq ','  ? add_subtitle
534                                         : $1 eq 'F1' ? prev_subtitle
535                                         : $1 eq 'F2' ? move_subtitle( -0.3 )
536                                         : $1 eq 'F3' ? move_subtitle( +0.3 )
537                                         : $1 eq 'F4' ? next_subtitle
538                                         : $1 eq 'F5' ? save_subtitles
539                                         : $1 eq 'F9' ? add_subtitle
540                                         : $1 eq 'F12' ? edit_subtitles
541                                         : warn "CUSTOM $1\n"
542                                         ;
543
544                                 } elsif ( $line =~ m{EDL}i ) {
545
546                                         print $to_mplayer qq|osd_show_text "$line"\n|;
547
548                                         if ( my $pos = time_pos ) {
549                                                 if ( $line =~ m{start}i ) {
550                                                         push @subtitles, [ $pos, $pos, '-' ];
551                                                 } else {
552                                                         $subtitles[ $#subtitles ]->[1] = $pos;
553                                                 }
554                                         }
555                                 }
556
557                                 $line = '';
558                         } else {
559                                 $line .= $chr;
560                         }
561
562
563                 } elsif ( $fileno == fileno $to_mplayer ) {
564 #                       warn "command";
565                 } else {
566                         die "invalid fileno $fileno";
567                 }
568         }
569
570 }
571